Search code examples
javajava.util.scanner

Java how to take user input


Can anyone please tell me what is wrong with my code, i was just trying to add scanner in java and it was showing me an error on package line

import java.util.Scanner;

package scaner;

public static void main(String[] args) {
    // TODO Auto-generated method stub
   Scanner in = new Scanner (System.in);
   System.out.println("enter your number");
   int number;
   number = in.nextInt();
   System.out.println("your number is" + " " + number);
}

}


Solution

  • First of all, the main method must be inside a class. Also, delete the "package scaner;" line. If you want, you can also simplify the code:

    import java.util.Scanner;
    
    public class className{
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            System.out.println("Your number is: " + number);
        }
    }