scanner中的nextInt方法
时间: 2023-05-15 17:08:05 浏览: 60
nextInt方法是Scanner类中的一个方法,用于读取下一个整数。它会跳过任何空格和换行符,并返回输入中的下一个整数。如果输入不是整数,则会抛出InputMismatchException异常。以下是nextInt方法的示例代码:
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println("您输入的整数是:" + num);
相关问题
scanner.nextInt()
The method scanner.nextInt() is a Java method used to read the next integer value from the input stream provided by the Scanner object. It scans the input stream for the next token that represents an integer value and returns that value as an int data type. If the next token is not an integer, it throws an InputMismatchException.
Here is an example of using scanner.nextInt() to read an integer value from the console input:
```
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer value: ");
int num = scanner.nextInt();
System.out.println("You entered " + num);
}
}
```
In this example, the program prompts the user to enter an integer value, reads the input using scanner.nextInt(), and then displays the entered value on the console.
Scanner.nextInt()
`Scanner.nextInt()` 是 Java 中 `Scanner` 类的一个方法,用于从控制台或文件中读取下一个整数。它会扫描输入流中的下一个整数,并返回该整数值。如果输入不是一个合法的整数,则会抛出 `InputMismatchException` 异常。例如:
```java
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = scanner.nextInt();
System.out.println("您输入的整数是:" + num);
}
}
```
以上代码会提示用户输入一个整数,然后使用 `Scanner.nextInt()` 方法读取用户输入的整数,并输出到控制台上。