为什么按回车键后没有打印?

huangapple go评论104阅读模式
英文:

Why isn't printing if i press enter?

问题

以下是已翻译的代码部分:

  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Main {
  7. public static void main(String[] args) {
  8. Scanner input = new Scanner(System.in);
  9. int count = 1;
  10. while (input.hasNext()) {
  11. String s = input.nextLine();
  12. System.out.println(count + " " + s);
  13. count++;
  14. }
  15. input.close();
  16. }
  17. }

如果您需要进一步的帮助,请告诉我。

英文:

Here is a problem in hackerrank. I am a noob in java so am facing a problem. In the code logic if i press enter means \n nextLine() will get it and will print number 1 but if I press enter it does print 1 but when I input a string it will print all the previous number why?

  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Main {
  7. public static void main(String[] args) {
  8. Scanner input = new Scanner(System.in);
  9. int count = 1;
  10. while (input.hasNext()) {
  11. String s = input.nextLine();
  12. System.out.println(count + " " + s);
  13. count++;
  14. }
  15. input.close();
  16. }
  17. }

My current result is:

  1. (enter)//input
  2. //no output
  3. (enter)//input
  4. //no output
  5. (enter)//input
  6. //no output
  7. Hello World! //input
  8. 1
  9. 2
  10. 3
  11. 4 Hello World!//output

But shouldn't it be like

  1. (enter)//input
  2. 1 //output
  3. (enter)//input
  4. 2 //output
  5. (enter)//input
  6. 3 //output
  7. Hello World!//input
  8. 4 Hello World! //output

答案1

得分: 3

问题在于input.hasNext()不包括空白的新行。你应该将它更改为input.hasNextLine()以产生期望的效果,就像下面的示例中一样:

  1. public class Main {
  2. public static void main(String[] args) {
  3. Scanner input = new Scanner(System.in);
  4. int count = 1;
  5. while (input.hasNextLine()) {
  6. String s = input.nextLine();
  7. System.out.println(count + " " + s);
  8. count++;
  9. }
  10. input.close();
  11. }
  12. }
英文:

The issue is that input.hasNext() does not include an empty new line. You should change it to input.hasNextLine() to produce the desired effects, such as in the following:

  1. public class Main {
  2. public static void main(String[] args) {
  3. Scanner input = new Scanner(System.in);
  4. int count = 1;
  5. while (input.hasNextLine()) {
  6. String s = input.nextLine();
  7. System.out.println(count + " " + s);
  8. count++;
  9. }
  10. input.close();
  11. }
  12. }

huangapple
  • 本文由 发表于 2023年7月3日 04:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定