[英]How to answer a question with a string using the scanner class using java?
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我整个周末都在尝试找到一种方法来让我的程序使用扫描仪 class 来回答问题。例如,我需要让我的程序来回答这样的问题
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?你能给我指明正确的方向,让我知道如何让它在 Java 中工作吗? I want to understand the material but I have really tried all weekend.我想了解这些材料,但我整个周末都在努力。
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!");
}
}
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. 如果您不想对所有实际的单词解决方案(例如“ Lincoln”)进行编码,也可以要求用户选择一个数字/字母解决方案,因为您只有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. 这将使跟踪答案键变得容易。
Scanner input = new Scanner(System.in);
System.out.println("Who is on the 5 dollar bill?");
String userinput = input.nextLine(); //get a name from user
if(userinput.equalsIgnoreCase("Lincoln"))
{ System.out.println("Answer is correct");}
else
{ System.out.println("Answer is wrong");}
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.