현재 사용자가 숫자를 입력하고 프로그램에서 단어를 선택하도록하는 프로그램을 실행하려고합니다. 그러나 나는 프로그램을 올바르게 작동시키는 것처럼 보일 수 없다. 색인을 변경하지 않고도 프로그램을 실행할 수 있습니다. 내가 여기서 누락 된 것이 있습니까? Random 함수를 가져 왔지만 마지막 부분을 알아내는 데 문제가 있습니다. 이 모든 작업은 NetBeans에서 수행됩니다. 당신은 임의의 클래스를 가져하지만 당신은 당신이 게시 된 코드를 사용하지 않을Arraylist의 숫자 색인을 무작위로 추출하려고합니다.
package arraywords;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Arraywords {
public static void main(String[] args) {
ArrayList<String>words = new ArrayList();
words.add("Token");
words.add("Magic");
words.add("People");
words.add("Racecar");
words.add("Xbox");
words.add("Puppy");
words.add("Destiny");
words.add("Knowledge");
words.add("Home");
words.add("Professional");
System.out.print("Choose a random number between 1 and 10 "
+ "to recieve a random word:\n");
int choice = 0;
Scanner scanner = new Scanner(System.in);//Scanner program
while (choice < 1 || choice > 10) {//The parametors for the users
System.out.println("Input a number:");
String message = scanner.next();//Prompt for user to input a number
try{
choice = Integer.parseInt(message);
}
catch(NumberFormatException e){
System.out.print("Please use numbers");
} /* The while loop watches the users input and is waiting for the user to input a number. Once they select a number. The word should be displayed. */
}
Integer index = choice -1; /* Since arrays begin with zero I had to account for that by adding the -1. */
System.out.printf("You entered #%d:\n> %s.", choice, words.get(index)); //Once the user has chosen a number the word will be displayed
}
}
왜이 자바 스크립트 태그가 무엇입니까? –
프로그램이 올바르게 실행 중입니다. 당신이 겪고있는 문제는 무엇입니까? – Yash
그것은 나를 위해 작동합니다 ... 내가 향상시킬 수있는 것은 결국 스캐너를 닫는 것입니다. – Stefan