Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

java number input console

  1. User

    java number input console

  2. Assistant

    To read a number from the console in Java, you can use the Scanner class.

    Here's an example of reading an integer from the console:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            
            System.out.print("Enter a number: ");
            int number = scanner.nextInt();
            
            System.out.println("You entered: " + number);
            
            scanner.close();
        }
    }
    

    In this example, we first create a Scanner object and pass System.in as the input source, which represents the standard input (console). We then use the nextInt() method of the Scanner class to read an integer input from the user. Finally, we print the entered number to the console.

    Don't forget to call the close() method of the Scanner object at the end to release any resources associated with it.