0

i keep getting a ';' is expected at the checkBinary(String num) { ^ error, yet i can't find any place for a ";". I have only been studying java for a few days so the problem could be something obvious i haven't learnt yet. Please provide a detailed explanation in way i could use it to prevent the problem in later projects. Thank you in advance!

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;
   }

}

1 Answers1

1

You need to move your checkBinary method outside of the main method. You cannot nest methods in java without declaring an inner class.

This should work:

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");
        }
    } 
}

If you want to know how to go about solving this with a nested class, there are numerous other questions/examples on SO. Like this one Can methods in java be nested and what is the effect? or In java what are nested classes and what do they do?

Community
  • 1
  • 1
jkeuhlen
  • 4,401
  • 23
  • 36