简体   繁体   English

“类型不匹配:无法从 int 转换为布尔值”我不知道错误究竟是什么

[英]"Type mismatch: cannot convert from int to boolean" I don't know what the error actually is

My teacher for the Java class went over an example with his students and I ended up with an error and I don't understand what is wrong.我的 Java 课老师和他的学生一起复习了一个例子,我最终得到了一个错误,我不明白出了什么问题。 All I know is that the error is "Type mismatch: cannot convert from int to boolean".我所知道的是错误是“类型不匹配:无法从 int 转换为布尔值”。 The issue is on the line that has "input.length" in it that entire section of code begins with "public boolean validate(String input)"问题在于其中包含“input.length”的那一行代码的整个部分都以“public boolean validate(String input)”开头

There was no suggestions to fix the issue so I have no idea what to try.没有解决问题的建议,所以我不知道该尝试什么。 I don't know enough about Java to fix the issue.我对 Java 的了解不够,无法解决这个问题。

import java.util.Scanner;

public class Application {
public void start(){
    Scanner scan = new Scanner(System.in);

    while(true)//trap
    {
        System.out.println("Enter an integer: ");
        int x = scan.nextInt();//could cause exception
        String s = scan.next();

        if(validate(s)){
            System.out.println("You entered "+s);
            System.out.println("Input is valid");
        }else{
            System.out.println("You entered "+s);
            System.out.println("Input is NOT valid");
        }
    }//end while


}//end start

public boolean validate(String input){
    //loop through strings char array looking for #
    for(int i = 0;input.length();i++){
        char c = input.charAt(i);
        if(!Character.isDigit(c)){//if char not #
            return false;
        }
    }

    return true;
}



}//end class

Expected results are to figure out what the issue is.预期结果是找出问题所在。

Normally it is helpful to include the line number where the error is, but I think I've found the issue anyway.通常包含错误所在的行号会很有帮助,但我想我还是找到了问题所在。 You have a for loop written:你写了一个for循环:

for(int i = 0;input.length();i++){

The second condition in a for loop is supposed to be a boolean condition indicating if the loop should continue or not. for 循环中的第二个条件应该是一个布尔条件,指示循环是否应该继续。 input.length(); returns an int not a boolean .返回一个int而不是boolean

I believe you want to loop through the whole of input, in which case you should use:我相信你想遍历整个输入,在这种情况下你应该使用:

for (int i = 0; i < input.length(); i++) {

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

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