gpt4 book ai didi

java - (';' 预期 boolean 值 checkBinary(String num) {^) 需要帮助查找错误

转载 作者:行者123 更新时间:2023-12-01 11:14:42 24 4
gpt4 key购买 nike

我不断收到“;”预计会出现 checkBinary(String num) { ^ 错误,但我找不到任何“;”的位置。我只学习了几天java,所以问题可能是我还没有学过的明显问题。请提供详细的解释,以便我可以使用它来防止以后的项目中出现问题。预先感谢您!

import java.io.*;
import java.util.Scanner;

public class checkbinary
{
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}

boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}

}

最佳答案

您需要将 checkBinary 方法移到主方法之外。如果不声明内部类,则无法在 java 中嵌套方法。

这应该有效:

import java.io.*;
import java.util.Scanner;

public class checkbinary
{
public boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}

public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
}
}

如果您想知道如何使用嵌套类来解决这个问题,那么还有许多其他问题/示例。喜欢这个Can methods in java be nested and what is the effect?In java what are nested classes and what do they do?

关于java - (';' 预期 boolean 值 checkBinary(String num) {^) 需要帮助查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31975158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com