java 如何使用java使用scanner类回答带有字符串的问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4986353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:57:22  来源:igfitidea点击:

How to answer a question with a string using the scanner class using java?

javajava.util.scanner

提问by Cferrel

I have been trying all weekend to find a way to get my program to answer a question using a sting with a scanner class. For example I need to get my program to answer a question like

我整个周末都在尝试找到一种方法,让我的程序使用扫描仪类的刺来回答问题。例如,我需要让我的程序回答这样的问题

Who is on the 5 dollar bill?

5 美元的钞票上是谁?

Input would be Lincoln and other inputs would be invalid the question will have 3 choices so the logic has to work.

输入将是林肯,其他输入将无效,问题将有 3 个选择,因此逻辑必须起作用。

Can you point me in the right direction on how to get this to work in Java? I want to understand the material but I have really tried all weekend.

你能指出我如何让​​它在 Java 中工作的正确方向吗?我想了解材料,但我整个周末都在尝试。

回答by Hanna

If I understood your question properly, then this should point you in the right direction:

如果我正确理解了您的问题,那么这应该为您指明正确的方向:

Import the Scanner:

导入扫描仪:

import java.util.Scanner;

Then, here is the method you'd want to call:

然后,这是您要调用的方法:

public void myScanner () {
     Scanner scan = new Scanner(System.in); //Creates a new scanner
     System.out.println("Who is on the 5 dollar bill?"); //Asks question
     String input = scan.nextLine(); //Waits for input
     if (input.equalsIgnoreCase("Lincoln")) { //If the input is Lincoln (or any case variant of Lincoln)
          System.out.println("Correct!");
     }
     else { //If the input is anything else
          System.out.println("Incorrect!");
     }
}

回答by donnyton

If you don't want to encode all the actual word solutions (like "Lincoln") you can also just ask the user to pick a number/letter solution since you only have 3.

如果您不想编码所有实际的单词解决方案(如“林肯”),您也可以要求用户选择一个数字/字母解决方案,因为您只有 3 个。

 Scanner input = new Scanner(System.in);
 System.out.println("Who is on the 5 dollar bill?  1. Lincoln 2. Somebody 3. Someone");
 String userChoice = scan.nextInt();    //get a number from user
 if(userChoice == 1)
       System.out.println("Correct answer!");
 else
       System.out.println("Wrong answer!");

This would make it easy to keep track of the answer key.

这将使跟踪答案密钥变得容易。