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

标签 java multiplication bluej

我在 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/

相关文章:

java - spring cloud stream kafka背压

java - 查看 Maven Artifact 的包

java - 在其他类中使用对象变量

Java:访问不同类中的不同变量以在条件语句中使用

java - 计算胜/负、胜率和总胜率

java - 将 genio 与数组结合使用

java - 登录接口(interface)方法

javascript - 如何在另一个文件中使用js变量

python - 如何将列表中的所有整数相乘

c++ - 3×3矩阵乘法