我问用户他们是否想玩游戏..
System.out.println("Would you like to play");
read in yes or no value
if yes (display text)
else (display other text)
我之前在程序中使用过扫描仪,我只需要再次使用它。我是否需要使用新变量声明另一个新的变量?
答案 0 :(得分:2)
String yesOrNo = System.in.readLine();
String textToDisplay = (yesOrNo.equals("Yes")) ? "text to display when yesOrNo equals yes" : "text to display when YesOrNo equals no";
答案 1 :(得分:2)
使用此方法:
scanner.nextBoolean()
那么它就是:
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.nextBoolean()==true) {
System.out.println("This will be fun");
} else {
System.out.println("Maybe next time");
}
修改
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
String val = scanner.next();
if(val.equalsIgnoreCase("y")||val.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(val.equalsIgnoreCase("n")||val.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
答案 2 :(得分:1)
为了简单起见,您可以使用以下内容:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
System.out.println("Would you like to play: 'y' or 'yes' to accept; 'n' or 'no' to reject; 'q' to quit:");
Scanner scanner = new Scanner(System.in);
String token = "";
while(scanner.hasNextLine())
{
token = scanner.nextLine().trim();
if(token.equalsIgnoreCase("q")) System.exit(0);
if(token.equalsIgnoreCase("y")||token.equalsIgnoreCase("yes"))
{
System.out.println("Thanks for your interest!");
System.exit(0);
}
else if (token.equalsIgnoreCase("n")||token.equalsIgnoreCase("no"))
{
System.out.println("That's a pity!");
System.exit(0);
}
else
{
System.out.println("Oops, not a valid input!");
}
}
}
}
答案 3 :(得分:1)
我只是偶然发现了这个问题,而且Chad M的答案是正确的,但是 - 就像上面提到的一些评论者 - 有一些错误。所以这是我没有错误的实现(这只是将用户输入保存到字符串变量的问题):
Scanner scanner = new Scanner(System.in);
String userInput = scanner.next();
if(userInput.equalsIgnoreCase("y") || userInput.equalsIgnoreCase("yes")) {
// y or yes
} else {
// other character
}
答案 4 :(得分:0)
根据dragon66的推荐,我正在实现与用户输入相比预定义输入的字符串比较。
System.out.println("Would you like to play? Or press Q to exit"):
Scanner scanner = new Scanner(System.in);
String affirmative = "yes";
String affirmative2 = "y";
String negative = "no";
String negative2 = "n";
String quit = "q";
if(scanner.next().equalsIgnoreCase(affirmative)||scanner.next().equalsIgnoreCase(affirmative2)) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase(negative)||scanner.next().equalsIgnoreCase(negative2)) {
System.out.println("Maybe next time");
} else if(scanner.next().equalsIgnoreCase(quit)){
System.out.println("Good bye");
System.exit();
} else {
System.out.println("Invalid character");
}