简体   繁体   English

JGrasp中的`If语句`

[英]The `If statement ` in JGrasp

How do I change the code.... 我该如何更改代码...。

if (yourAnswer = numberOne + numberTwo)
{
   System.out.println("That is correct!");
   counter = counter + 1;
}
else
{
   System.out.println("That is incorrect!");
}

This does not seem to be working for me. 这似乎不适用于我。 Can anyone help me?. 谁能帮我?。 The debugger is saying: 调试器在说:

RandomNumbersProgramThree.java:21: error: incompatible types: int cannot be converted to boolean". RandomNumbersProgramThree.java:21:错误:类型不兼容:int无法转换为boolean。

You cannot associate a number with a Boolean value. 您不能将数字与布尔值关联。 A boolean is true or false, not a number, however you can create a variable that indicates if a certain number represents true or false. 布尔值是对还是错,不是数字,但是您可以创建一个变量,该变量指示某个数字代表对还是错。 Is this your entire program? 这是您的整个程序吗? I would like to see what "yourAnswer", "numberOne", and "numberTwo" are stored. 我想看看存储了什么“ yourAnswer”,“ numberOne”和“ numberTwo”。 but for now I will write a pseudo-program to explain the theory. 但现在我将编写一个伪程序来解释该理论。

   import java.util.*;
   public class ExampleProgram
    {
   public static void main(String[] args)
     {
     System.out.println("Please enter two numbers");
     Scanner answer = new Scanner (System.in);

     int yourAnswer = answer.nextInt();
     int numberOne = 1;
     int numberTwo = 2;


     if (yourAnswer == (numberOne + numberTwo))
     {
        System.out.println("That is correct!");
     }
     else
     {
        System.out.println("That is incorrect!");
     }
  }
}

This program will ask the user to input a number, for example the number "3". 该程序将要求用户输入一个数字,例如数字“ 3”。 It will then compare that number to the two numbers you declares, "numberOne" which equals the value of one, and "numberTwo" which equals the value of two. 然后它将把该数字与您声明的两个数字进行比较,“ numberOne”等于1的值,“ numberTwo”等于2的值。 Therefore, in the "IF" statement it says, "If (yourAnswer == (numberOne + numberTwo))" which means that 1 + 2 = 3, if the users answer is 3, then 3 = 3 and the result will come back as true. 因此,在“ IF”语句中表示“ If(yourAnswer ==(numberOne + numberTwo))”,这意味着1 + 2 = 3,如果用户回答为3,则3 = 3,结果将返回确实如此。

In the if statement, you are using an '=' sign, this type of equal sign is not a comparison '=' but is used to set a value to an variable. 在if语句中,您使用的是“ =”号,这种等号不是比较号“ =”,而是用于为变量设置值。 ie, int x = 2; 即int x = 2; The type of equals you need is the type that is used in comparisons, which is ==. 您需要的等于类型是比较中使用的类型,即==。 You always use == when dealing with boolean comparisons 在处理布尔比较时,总是使用==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM