Java Scanner&用户输入文本框

时间:2015-01-19 01:50:31

标签: 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。 我该如何解决这个问题? 感谢

2 个答案:

答案 0 :(得分:1)

你必须解决这个问题:

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,但你永远不会进入一个可以突破的循环。

答案 1 :(得分:0)

是的,就像吸收说的那样,=和==是不同的。如果使用=,则实际上是在赋值,而在使用==时,实际上是在比较两个不同的值。

此外,除非您使用switch语句,否则不应使用break。如果有的话,我认为你错误地通过

 return 

相关问题