【问题标题】:(';' expected boolean checkBinary(String num) {^) Need help finding the error(';' expected boolean checkBinary(String num) {^) 需要帮助查找错误
【发布时间】:2015-08-12 20:51:17
【问题描述】:

我不断得到一个';'预计在 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;
   }

}

【问题讨论】:

  • 方法内的方法不允许

标签: java compiler-errors


【解决方案1】:

您需要将 checkBinary 方法移到 main 方法之外。如果不声明内部类,就不能在 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");
        }
    } 
}

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

【讨论】:

  • 感谢您的信息,这正是我想要的。
  • @LouisSyropoulo 如果这解决了您的问题,请不要忘记“接受”它作为答案!
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 2022-01-17
  • 2012-05-15
相关资源
最近更新 更多