简体   繁体   English

使用扫描仪从用户那里获得答案,然后将结果与arraylist进行比较。

[英]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. 我试图在Java中创建一个程序,以使用扫描仪从用户那里得到答案,然后应将此结果与数字数组列表(即多项选择题)进行比较,然后打印出字符串。 I can get the value in the arraylist to compare to value and print, but when inputting the scanner answer nothing happens. 我可以在arraylist中获取值以与值进行比较并进行打印,但是当输入扫描仪时,没有任何反应。

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. 您需要调用answer.readLine()并将其存储在字符串变量中。

Then you will need to loop through the arraylist and compare that to the value you stored from the scanner. 然后,您将需要遍历arraylist并将其与您从扫描仪存储的值进行比较。

What's the point of setter and getter for a local inaccessible variable? 局部不可访问变量的setter和getter有什么意义?

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. 如James所述,您需要通过调用.nextLine()来读取带有Scanner对象的输入字符串,而不仅仅是将整个Scanner对象与target进行比较。 Next, you need to replace the == with .equals(answersArray.get(0)) and it'll work 接下来,您需要将==替换为.equals(answersArray.get(0))即可

Add answer.next() to take the input from the keyboard! 添加answer.next()以从键盘获取输入! You are just initializing but not giving reference. 您只是在初始化,但没有提供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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