inputing number in java

http‮s‬://www.lautturi.com
inputing number in java

To input a number in Java, you can use the Scanner class or the BufferedReader class.

Here is an example of how to use the Scanner class to input a number:

import java.util.Scanner;

public class Main {
    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("You entered: " + number);
        sc.close();
    }
}

In this example, the Scanner class is used to read a line of input from the console. The nextInt() method is used to read the next token in the input as an integer, and the value is then printed to the console.

Here is an example of how to use the BufferedReader class to input a number:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter a number: ");
        int number = Integer.parseInt(br.readLine());
        System.out.println("You entered: " + number);
        br.close();
    }
}

In this example, the BufferedReader class is used to read a line of input from the console. The readLine() method is used to read the line as a String, and the Integer.parseInt() method is used to parse the String as an integer. The value is then printed to the console.

For more information on the Scanner class and the BufferedReader class in Java, you can refer to the Java documentation and the Java tutorial.

Created Time:2017-11-01 22:29:52  Author:lautturi