gpt4 book ai didi

Java 扫描器和用户输入文本框

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

我在 BlueJ IDE 中使用 Java 代码时遇到了一些问题。我想做的是问用户:“1 x 3 是什么?”并有一个文本框,用户可以在其中输入答案,然后按按钮提交答案。如果答案正确,程序将显示一条消息“正确”,如果答案错误,则显示“不正确,请重试”。这是我编写的代码:

Scanner input = new Scanner(System.in);
//prompt the user to enter thier answer to the question
//create two labels to explain input

double answer = 3; //the correct answer to the multiplication question

JLabel labelAnswer = new JLabel("What is 1 x 3?"); //ask user this
double userAnswer = input.nextDouble();
//prompt the user to enter the gallons
if (userAnswer = 3) //if the user enters 3 into the text box, a message will be displayed saying: Correct!{
{ if (userAnswer == 3)
{System.out.println("Correct!");

break;
}
if (userAnswer != 3) //if the user enters anything others than 3, it is incorrect
{
System.out.println("Incorrect, Please try again!");

}

我收到的错误代码表明 double 值无法转换为 boolean 值。我该如何解决这个问题?谢谢

最佳答案

你必须解决这个问题:

if(userAnswer = 3)

将其更改为:

if(userAnswer == 3)

我还可以推荐这个以节省空间吗?

if(userAnswer == 3)
System.out.println("Correct!");
else
System.out.println("Incorrect, Please try again!");

而不是:

if (userAnswer = 3) //if the user enters 3 into the text box, a message will be displayed saying: Correct!{
{ if (userAnswer == 3)
{System.out.println("Correct!");

break;
}
if (userAnswer != 3) //if the user enters anything others than 3, it is incorrect
{
System.out.println("Incorrect, Please try again!");

}

此外,您调用 break,但您永远不会进入可以中断的循环。

关于Java 扫描器和用户输入文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28016884/

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