How to read integer value from the standard input in Java
To read an integer value from the standard input (keyboard) in Java, you can use the Scanner
class from the java.util
package.
Here is an example of how you can use the Scanner
class to read an integer value from the standard input:
import java.util.Scanner;
// ...
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
In this example, a Scanner
object is created and connected to the standard input (keyboard). The nextInt()
method of the Scanner
class is then used to read an integer value from the input.
You can also use the hasNextInt()
method of the Scanner
class to check if there is an integer value available to be read, and the nextLine()
method to read a line of text from the input.
Here is an example of how you can use these methods to read multiple integer values from the standard input:
import java.util.Scanner;
// ...
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
// do something with the integer value
}
I hope this helps! Let me know if you have any other questions.