gpt4 book ai didi

Java:使用扫描仪读取 boolean 值失败。

转载 作者:行者123 更新时间:2023-12-01 07:37:08 26 4
gpt4 key购买 nike

import java.util.Scanner;

public class Cardhelp2{

private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};

public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);

//displays the cards

___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);

if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");

}
}
}

我无法理解为什么最后部分不起作用,我被告知我需要更改scanner.next();到一个变量,但我不知道如何做到这一点并使代码正常工作。有没有一种简单的方法可以读取用户的答案,然后向用户显示响应?

谢谢

最佳答案

你的条件表达式

if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) 

调用 scanner.next() 两次,这意味着第二次调用将读取/等待更多输入。相反,您只需调用它一次,存储结果并在比较中使用它:

String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))

关于Java:使用扫描仪读取 boolean 值失败。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com