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

iaqfqrcu  于 2021-08-25  发布在  Java
关注(0)|答案(20)|浏览(486)

我正在使用 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() 按照我的要求执行。

piah890a

piah890a1#

sc.nextLine() 与解析输入相比,它的性能更好。因为就性能而言,这将是好的。

eimct9ow

eimct9ow2#

问题在于input.nextint()方法-它只读取int值。因此,当您继续阅读input.nextline()时,您将收到

axkjgtzd

axkjgtzd3#

为什么每次阅读都不使用新的扫描仪呢?如下图所示。使用这种方法,您将不会面对您的问题。

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

a1o7rhls4#

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

  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)
yks3o0rb

yks3o0rb5#

作为 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);
ruarlubt

ruarlubt6#

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

iqih9akk

iqih9akk7#

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

  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();
wztqucjr

wztqucjr8#

如果我期望一个非空的输入
避免:
–如果以下输入被未经检查的 scan.nextLine() 作为解决办法
–仅部分读取行导致数据丢失,因为 scan.nextLine() 被替换为 scan.next() (输入:“Yeppie ya yeah”)
–  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
展开查看全部
smtd7mpg

smtd7mpg9#

  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. }
ncecgwcz

ncecgwcz10#

我想我参加晚会已经很晚了。。
如前所述 input.nextLine() 得到int值后,将解决您的问题。您的代码不起作用的原因是,您的输入(输入int的地方)中没有其他内容可存储 string1 . 我只想对整个主题多说一点。
将NestRoin()视为扫描器类中的NeXFoT()方法中的奇数。让我们举一个很快的例子。假设我们有两行代码,如下所示:

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

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

pcww981p

pcww981p11#

那是因为 Scanner.nextInt 方法不会读取通过单击“enter”创建的输入中的换行符,因此调用 Scanner.nextLine 读取该换行符后返回。
在使用时,您将遇到类似的行为 Scanner.nextLine 之后 Scanner.next() 或任何 Scanner.nextFoo 方法(除 nextLine 本身)。
解决方法:
要么放一个 Scanner.nextLine 每次之后都打电话 Scanner.nextIntScanner.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();
展开查看全部
ghg1uchk

ghg1uchk12#

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

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

holgip5t13#

如果您想快速扫描输入而不被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....
展开查看全部
6fe3ivhb

6fe3ivhb14#

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

  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();
k5ifujac

k5ifujac15#

而不是 input.nextLine() 使用 input.next() ,这应该可以解决问题。
修改代码:

  1. public static Scanner input = new Scanner(System.in);
  2. public static void main(String[] args)
  3. {
  4. System.out.print("Insert a number: ");
  5. int number = input.nextInt();
  6. System.out.print("Text1: ");
  7. String text1 = input.next();
  8. System.out.print("Text2: ");
  9. String text2 = input.next();
  10. }

相关问题