简体   繁体   中英

Using a scanner to get answer from user, to then compare result with arraylist.

I'm trying to create a program in java to get an answer from a user using a scanner, this result should then be compared to an arraylist of numbers, ie a multiple choice question, and then print out a string. I can get the value in the arraylist to compare to value and print, but when inputting the scanner answer nothing happens.

cheers

'public static void main (String [] args){
    ArrayList<String> answersArray = new ArrayList<String>();
    answersArray.add("4");
    answersArray.add("5");
    answersArray.add("10");
    answersArray.add("20");

    System.out.println("Please select the answer from the list below\n" + answersArray);

    Scanner answer = new Scanner(System.in);
    String value = ExamQuestionSimpleChoice.answer;

    if   ( value == (answersArray.get(0))){
    System.out.println("This answer is correct, you gained:  "  );
    }
    }

    public static String getValue() {
    return value;
}
public static void setValue(String value) {
    ExamQuestionSimpleChoice.value = value;
}`

Instantiating the scanner will just prepare the scanner object. You need to call answer.readLine() and store that in a string variable.

Then you will need to loop through the arraylist and compare that to the value you stored from the scanner.

What's the point of setter and getter for a local inaccessible variable?

as James mentioned you need to read the input string with Scanner object by calling the .nextLine() not just compare the whole scanner object with target. Next, you need to replace the == with .equals(answersArray.get(0)) and it'll work

Add answer.next() to take the input from the keyboard! You are just initializing but not giving reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM