Java.util.Scanner 类

java.util.Scanner.nextInt() 方法用于将输入的下一个标记扫描为 int。调用 nextInt() 形式的此方法的行为与调用 nextInt(radix) 的行为完全相同,其中 radix 是此扫描器的默认基数。

语法

public int nextInt()
  • 1

参数

不需要参数。

返回值

返回从输入扫描的int。

Exception

  • 如果下一个标记与 Float 正则表达式不匹配或超出范围,则抛出 InputMismatchException
  • 抛出 NoSuchElementException(如果输入已用尽)。
  • 抛出 IllegalStateException(如果此扫描仪已关闭)。

示例:

在下面的示例中,java.util.Scanner.nextInt() 方法用于将输入的下一个标记扫描为 int。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //要扫描的字符串
    String MyString = "Hello World 10 + 20 = 30.0";

    //创建扫描仪
    Scanner MyScan = new Scanner(MyString);

    while(MyScan.hasNext()) {
      //如果下一个是 int
      if(MyScan.hasNextInt())
        System.out.println("Int value is: "+ MyScan.nextInt());
      //如果下一个不是 int
      else
        System.out.println("No Int Value found: "+ MyScan.next());
    }

    //关闭扫描仪
    MyScan.close();
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

上述代码的输出将是:

No Int Value found: Hello
No Int Value found: World
Int value is: 10
No Int Value found: +
Int value is: 20
No Int Value found: =
No Int Value found: 30.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7