Java:不兼容的类型(int/boolean)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18325314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:31:30  来源:igfitidea点击:

Java: Incompatible Types (int/boolean)

javabooleanintincompatibletypeerror

提问by Adam Hussain

import java.io.*;
public class AdamHmwk4 {
    public static void main(String [] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int counter1;
        int counter2;
        int counter3;
        String answer = "";

        System.out.println("Welcome to Adam's skip-counting program!");
        System.out.println("Please input the number you would like to skip count by.");
        counter1 = Integer.parseInt(br.readLine());

        System.out.println("Please input the number you would like to start at.");
        counter2 = Integer.parseInt(br.readLine());

        System.out.println("Please input the number you would like to stop at.");
        counter3 = Integer.parseInt(br.readLine());

        System.out.println("This is skip counting by" + counter1 + ", starting at" + counter2  + "and ending at" + counter3 +":");

        while (counter2 = counter3) {
            counter2 = counter2 + counter1;
            counter3 = counter2 + counter1;
        }
    }
}

I am trying to make skip-counting program. When I compile this code, the line while(counter2 = counter3){shows up as a Incompatible Types error. The compiler says it found an "int" but it requires a "boolean". Please keep in mind that I am a newbie, so I have not learned booleans in my Java class yet.

我正在尝试制作跳过计数程序。当我编译此代码时,该行while(counter2 = counter3){显示为 Incompatible Types 错误。编译器说它找到了一个“int”,但它需要一个“boolean”。请记住,我是一个新手,所以我还没有在我的 Java 课上学习布尔值。

回答by rgettman

You can't compare values with =, which is the assignment operator. Use ==to compare your values. Change

您不能将值与=,这是赋值运算符。使用==比较你的价值观。改变

while(counter2 = counter3){

to

while(counter2 == counter3){

Here's an introductory page for Java operators.

这是Java 运算符介绍页面

回答by Mik378

You use an assignment operator:

您使用赋值运算符:

while(counter2 = counter3)

instead of the equality operator:

而不是等号运算符:

while(counter2 == counter3)

回答by Juned Ahsan

Here is the problem:

这是问题所在:

               while(counter2 = counter3)

=is used for assignment and post this statement, counter2 will be assigned the value of counter3. Hence your while loop will not behave the way you want. You need to use ==for comparing counter2 to counter 3

=用于赋值并发布此语句,counter2 将被分配 counter3 的值。因此,您的 while 循环不会按照您想要的方式运行。您需要==用于比较 counter2 和 counter 3

               while(counter2 == counter3)