-2

I'm trying to create a Java program that prompts the user to enter a number well guess the number with a void method called CheckNum (int num) and the decision statements in the void method CheckNum, checks if the number entered is 100, if that is true, the following message “Number is correct!"

So far this is what I have created:

import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        checkNum();
    }

    public static void checkNum()
    {

        System.out.println("Enter a number: ");
        int guess= sc.nextInt();
        int number=(int)(Math.random()*100)+1;
        System.out.println("The number is "+number);
        if(guess>=1 && guess<=100)
        {
            if(guess==number)
                System.out.println("The number is right!");
            else
                System.out.println("Wrong!");
        }
        else
        {
            System.out.println("Make it a 1-100 please!");
            checkNum();
        }


    }
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Neo
  • 1
  • 1

1 Answers1

2

You can't just use variable from other method. Here are options for you

  • Define the Scanner as static for the class

    public class Main{
        static Scanner sc = new Scanner(System.in);
    
        public static void main(String[] args){
            checkNum();
        }
        public static void checkNum(){...}
    }
    
  • Pass the Scanner as a parameter

    public class Main{    
        public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            checkNum(sc);
        }
        public static void checkNum(Scanner sc){...}
    }
    
  • Define it only in the method

    public class Main{    
        public static void main(String[] args){
            checkNum();
        }
        public static void checkNum(){
            Scanner sc = new Scanner(System.in)
            ...
        }
    }
    
azro
  • 53,056
  • 7
  • 34
  • 70