英文:
Why isn't printing if i press enter?
问题
以下是已翻译的代码部分:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = 1;
while (input.hasNext()) {
String s = input.nextLine();
System.out.println(count + " " + s);
count++;
}
input.close();
}
}
如果您需要进一步的帮助,请告诉我。
英文:
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?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = 1;
while (input.hasNext()) {
String s = input.nextLine();
System.out.println(count + " " + s);
count++;
}
input.close();
}
}
My current result is:
(enter)//input
//no output
(enter)//input
//no output
(enter)//input
//no output
Hello World! //input
1
2
3
4 Hello World!//output
But shouldn't it be like
(enter)//input
1 //output
(enter)//input
2 //output
(enter)//input
3 //output
Hello World!//input
4 Hello World! //output
答案1
得分: 3
问题在于input.hasNext()
不包括空白的新行。你应该将它更改为input.hasNextLine()
以产生期望的效果,就像下面的示例中一样:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = 1;
while (input.hasNextLine()) {
String s = input.nextLine();
System.out.println(count + " " + s);
count++;
}
input.close();
}
}
英文:
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:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = 1;
while (input.hasNextLine()) {
String s = input.nextLine();
System.out.println(count + " " + s);
count++;
}
input.close();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论