扫描仪在使用next()或nextfoo()后跳过nextline()?

hfwmuf9z  于 2021-07-12  发布在  Java
关注(0)|答案(21)|浏览(487)

我用的是 Scanner 方法 nextInt() 以及 nextLine() 用于读取输入。
看起来是这样的:

  1. System.out.println("Enter numerical value");
  2. int option;
  3. option = input.nextInt(); // Read numerical value from input
  4. System.out.println("Enter 1st string");
  5. String string1 = input.nextLine(); // Read 1st string (this is skipped)
  6. System.out.println("Enter 2nd string");
  7. String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)

问题是在输入数值后,第一个 input.nextLine() 跳过第二个 input.nextLine() 执行,因此我的输出如下所示:

  1. Enter numerical value
  2. 3 // This is my input
  3. Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
  4. Enter 2nd string // ...and this line is executed and waits for my input

我测试了我的应用程序,看起来问题在于使用 input.nextInt() . 如果我删除它,那么两者 string1 = input.nextLine() 以及 string2 = input.nextLine() 按我的意愿执行。

ztigrdn8

ztigrdn81#

sc.nextLine() 比解析输入更好。因为从性能上看,它是好的。

eivgtgni

eivgtgni2#

要解决此问题,只需执行scan.nextline(),其中scan是scanner对象的示例。例如,我用一个简单的hackerrank问题来解释。

  1. package com.company;
  2. import java.util.Scanner;
  3. public class hackerrank {
  4. public static void main(String[] args) {
  5. Scanner scan = new Scanner(System.in);
  6. int i = scan.nextInt();
  7. double d = scan.nextDouble();
  8. scan.nextLine(); // This line shall stop the skipping the nextLine()
  9. String s = scan.nextLine();
  10. scan.close();
  11. // Write your code here.
  12. System.out.println("String: " + s);
  13. System.out.println("Double: " + d);
  14. System.out.println("Int: " + i);
  15. }

}

展开查看全部
w8f9ii69

w8f9ii693#

问题在于input.nextint()方法-它只读取int值。因此,当您继续使用input.nextline()读取时,会收到“\n”enter键。因此,要跳过此操作,必须添加input.nextline()。希望这一点现在应该清楚了。
试着这样做:

  1. System.out.print("Insert a number: ");
  2. int number = input.nextInt();
  3. input.nextLine(); // This line you have to add (It consumes the \n character)
  4. System.out.print("Text1: ");
  5. String text1 = input.nextLine();
  6. System.out.print("Text2: ");
  7. String text2 = input.nextLine();
5jdjgkvh

5jdjgkvh4#

为什么每次阅读都不使用新的扫描仪呢?就像下面一样。用这种方法你将不会面对你的问题。

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

z9smfwbn5#

使用此代码可以解决您的问题。

  1. System.out.println("Enter numerical value");
  2. int option;
  3. option = input.nextInt(); // Read numerical value from input
  4. input.nextLine();
  5. System.out.println("Enter 1st string");
  6. String string1 = input.nextLine(); // Read 1st string (this is skipped)
  7. System.out.println("Enter 2nd string");
  8. String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
wko9yo5t

wko9yo5t6#

作为 nextXXX() 方法不读 newline ,除了 nextLine() . 我们可以跳过 newline 在阅读任何 non-string 价值( int 在这种情况下)使用 scanner.skip() 具体如下:

  1. Scanner sc = new Scanner(System.in);
  2. int x = sc.nextInt();
  3. sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
  4. System.out.println(x);
  5. double y = sc.nextDouble();
  6. sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
  7. System.out.println(y);
  8. char z = sc.next().charAt(0);
  9. sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
  10. System.out.println(z);
  11. String hello = sc.nextLine();
  12. System.out.println(hello);
  13. float tt = sc.nextFloat();
  14. sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
  15. System.out.println(tt);
mfpqipee

mfpqipee7#

在我的一个用例中,我有这样一个场景:读取一个字符串值,后跟几个整数值。我必须使用“for/while循环”来读取值。而上述建议在这种情况下都不起作用。
使用 input.next() 而不是 input.nextLine() 解决了这个问题。希望这对处理类似情况的人有所帮助。

8zzbczxx

8zzbczxx8#

使用两个扫描仪对象而不是一个

  1. Scanner input = new Scanner(System.in);
  2. System.out.println("Enter numerical value");
  3. int option;
  4. Scanner input2 = new Scanner(System.in);
  5. option = input2.nextInt();
w8ntj3qf

w8ntj3qf9#

如果我期望一个非空的输入
避免:
–  如果以下输入被未选中的 scan.nextLine() 作为解决方法
–  仅部分读取行导致数据丢失,因为 scan.nextLine() 被替换为 scan.next() (输入:“yippie 是的 是的“)
–  Exception 解析输入时抛出的 Scanner 方法(先读取,后解析)

  1. public static Function<Scanner,String> scanLine = (scan -> {
  2. String s = scan.nextLine();
  3. return( s.length() == 0 ? scan.nextLine() : s );
  4. });

用于上述示例:

  1. System.out.println("Enter numerical value");
  2. int option = input.nextInt(); // read numerical value from input
  3. System.out.println("Enter 1st string");
  4. String string1 = scanLine.apply( input ); // read 1st string
  5. System.out.println("Enter 2nd string");
  6. String string2 = scanLine.apply( input ); // read 2nd string
展开查看全部
gijlo24d

gijlo24d10#

  1. public static void main(String[] args) {
  2. Scanner scan = new Scanner(System.in);
  3. int i = scan.nextInt();
  4. scan.nextLine();
  5. double d = scan.nextDouble();
  6. scan.nextLine();
  7. String s = scan.nextLine();
  8. System.out.println("String: " + s);
  9. System.out.println("Double: " + d);
  10. System.out.println("Int: " + i);
  11. }
kx5bkwkv

kx5bkwkv11#

我想我去派对已经很晚了。。
如前所述,呼叫 input.nextLine() 得到int值后,问题就迎刃而解了。你的代码不起作用的原因是因为你的输入(输入int的地方)中没有其他东西可以存储 string1 . 我只想对整个主题多讲一点。
将nextline()看作scanner类中nextfoo()方法中的奇数。让我们举个简单的例子。。假设我们有两行代码,如下所示:

  1. int firstNumber = input.nextInt();
  2. int secondNumber = input.nextInt();

如果我们输入下面的值(作为一行输入)
54 234
我们的价值 firstNumber 以及 secondNumber 变量分别变为54和234。这样做的原因是,当nextint()方法接受值时,不会自动生成换行符(即\n)。它只需要“next int”就可以继续了。除nextline()外,其余的nextfoo()方法也是如此。
nextline()在获取一个值后立即生成一个新行提要;这就是@rohitjain所说的新行提要“已消耗”的意思。
最后,next()方法只取最近的字符串,而不生成新行;这使它成为在同一行中获取单独字符串的首选方法。
我希望这有帮助。。快乐的编码!

qjp7pelc

qjp7pelc12#

那是因为 Scanner.nextInt 方法不会读取通过按“enter”创建的输入中的换行符,因此 Scanner.nextLine 在读了新行之后返回。
在使用时,您会遇到类似的行为 Scanner.nextLine 之后 Scanner.next() 或任何 Scanner.nextFoo 方法(除 nextLine 本身)。
解决方法:
要么放一个 Scanner.nextLine 每次之后打电话 Scanner.nextInt 或者 Scanner.nextFoo 去消耗那条线的其余部分,包括新线

  1. int option = input.nextInt();
  2. input.nextLine(); // Consume newline left-over
  3. String str1 = input.nextLine();

或者,更好的是,通读输入 Scanner.nextLine 把你的输入转换成你需要的格式。例如,可以使用 Integer.parseInt(String) 方法。

  1. int option = 0;
  2. try {
  3. option = Integer.parseInt(input.nextLine());
  4. } catch (NumberFormatException e) {
  5. e.printStackTrace();
  6. }
  7. String str1 = input.nextLine();
展开查看全部
g6baxovj

g6baxovj13#

为了避免问题,请使用 nextLine(); 紧接着 nextInt(); 因为它有助于清除缓冲区。当你按下 ENTER 这个 nextInt(); 不捕获新行,因此跳过 Scanner 稍后再编码。

  1. Scanner scanner = new Scanner(System.in);
  2. int option = scanner.nextInt();
  3. scanner.nextLine(); //clearing the buffer
mec1mxoz

mec1mxoz14#

如果您想快速扫描输入而不被scanner类nextline()方法所迷惑,请使用自定义输入扫描器。

代码:

  1. class ScanReader {
  2. /**
  3. * @author Nikunj Khokhar
  4. * /
  5. private byte[] buf = new byte[4 * 1024];
  6. private int index;
  7. private BufferedInputStream in;
  8. private int total;
  9. public ScanReader(InputStream inputStream) {
  10. in = new BufferedInputStream(inputStream);
  11. }
  12. private int scan() throws IOException {
  13. if (index >= total) {
  14. index = 0;
  15. total = in.read(buf);
  16. if (total <= 0) return -1;
  17. }
  18. return buf[index++];
  19. }
  20. public char scanChar(){
  21. int c=scan();
  22. while (isWhiteSpace(c))c=scan();
  23. return (char)c;
  24. }
  25. public int scanInt() throws IOException {
  26. int integer = 0;
  27. int n = scan();
  28. while (isWhiteSpace(n)) n = scan();
  29. int neg = 1;
  30. if (n == '-') {
  31. neg = -1;
  32. n = scan();
  33. }
  34. while (!isWhiteSpace(n)) {
  35. if (n >= '0' && n <= '9') {
  36. integer *= 10;
  37. integer += n - '0';
  38. n = scan();
  39. }
  40. }
  41. return neg * integer;
  42. }
  43. public String scanString() throws IOException {
  44. int c = scan();
  45. while (isWhiteSpace(c)) c = scan();
  46. StringBuilder res = new StringBuilder();
  47. do {
  48. res.appendCodePoint(c);
  49. c = scan();
  50. } while (!isWhiteSpace(c));
  51. return res.toString();
  52. }
  53. private boolean isWhiteSpace(int n) {
  54. if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
  55. else return false;
  56. }
  57. public long scanLong() throws IOException {
  58. long integer = 0;
  59. int n = scan();
  60. while (isWhiteSpace(n)) n = scan();
  61. int neg = 1;
  62. if (n == '-') {
  63. neg = -1;
  64. n = scan();
  65. }
  66. while (!isWhiteSpace(n)) {
  67. if (n >= '0' && n <= '9') {
  68. integer *= 10;
  69. integer += n - '0';
  70. n = scan();
  71. }
  72. }
  73. return neg * integer;
  74. }
  75. public void scanLong(long[] A) throws IOException {
  76. for (int i = 0; i < A.length; i++) A[i] = scanLong();
  77. }
  78. public void scanInt(int[] A) throws IOException {
  79. for (int i = 0; i < A.length; i++) A[i] = scanInt();
  80. }
  81. public double scanDouble() throws IOException {
  82. int c = scan();
  83. while (isWhiteSpace(c)) c = scan();
  84. int sgn = 1;
  85. if (c == '-') {
  86. sgn = -1;
  87. c = scan();
  88. }
  89. double res = 0;
  90. while (!isWhiteSpace(c) && c != '.') {
  91. if (c == 'e' || c == 'E') {
  92. return res * Math.pow(10, scanInt());
  93. }
  94. res *= 10;
  95. res += c - '0';
  96. c = scan();
  97. }
  98. if (c == '.') {
  99. c = scan();
  100. double m = 1;
  101. while (!isWhiteSpace(c)) {
  102. if (c == 'e' || c == 'E') {
  103. return res * Math.pow(10, scanInt());
  104. }
  105. m /= 10;
  106. res += (c - '0') * m;
  107. c = scan();
  108. }
  109. }
  110. return res * sgn;
  111. }
  112. }

优点:

扫描输入速度比bufferreader快
降低时间复杂性
为下一个输入刷新缓冲区

方法:

scanchar()-扫描单个字符
scanint()-扫描整数值
scanlong()-扫描长度值
scanstring()-扫描字符串值
scandouble()-扫描双值
scanint(int[]数组)-扫描整个数组(整数)
scanlong(long[]数组)-扫描整个数组(long)

用法:

将给定的代码复制到java代码下面。
初始化给定类的对象 ScanReader sc = new ScanReader(System.in); 3.导入必要的类: import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; 4.从主方法抛出ioexception来处理异常5。使用提供的方法。6.享受

示例:

  1. import java.io.BufferedInputStream;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. class Main{
  5. public static void main(String... as) throws IOException{
  6. ScanReader sc = new ScanReader(System.in);
  7. int a=sc.scanInt();
  8. System.out.println(a);
  9. }
  10. }
  11. class ScanReader....
展开查看全部
bogh5gae

bogh5gae15#

如果要同时读取字符串和整数,解决方案是使用两个扫描仪:

  1. Scanner stringScanner = new Scanner(System.in);
  2. Scanner intScanner = new Scanner(System.in);
  3. intScanner.nextInt();
  4. String s = stringScanner.nextLine(); // unaffected by previous nextInt()
  5. System.out.println(s);
  6. intScanner.close();
  7. stringScanner.close();

相关问题