【问题标题】:nextInt() in javajava中的nextInt()
【发布时间】:2016-11-05 11:13:53
【问题描述】:

我听说 nextInt() 只读取整数并忽略末尾的 \n。 那么为什么下面的代码运行成功呢?

为什么我们输入 a 的值后没有错误,因为 \n 必须保留在缓冲区中, 所以在 b 处使用 nextInt() 应该会出错,但不会。为什么?

 import java.util.Scanner;

    public class useofScanner {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        int a = scanner.nextInt();
        int b=scanner.nextInt();
        System.out.println(a+b);
    }
    }

【问题讨论】:

  • 它会忽略\n,但不会在\n 上抛出异常,它只是将其视为分隔符。
  • 缓冲区中剩余的 \n 会怎样?
  • nextInt 使用/丢弃前导空格,无论您使用多少空格、制表符或换行符。

标签: java exception io


【解决方案1】:

扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。然后可以使用各种 next 方法将生成的标记转换为不同类型的值。

例如,此代码允许用户从 System.in 中读取数字:

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

作为另一个示例,此代码允许从文件 myNumbers 中的条目分配长类型:

  Scanner sc = new Scanner(new File("myNumbers"));
  while (sc.hasNextLong()) {
      long aLong = sc.nextLong();
  }

扫描器还可以使用空格以外的分隔符。这个例子从一个字符串中读取了几个项目:

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

打印以下输出:

 1
 2
 red
 blue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多