英文:
User Input of sentence in Java
问题
以下是翻译好的内容:
每当我在 Java 中使用 sc.nextLine
,就会出现这个错误。它会跳过一行。有人知道如何修复这个问题吗?sc.nextLine
在多个测试用例中失败,因为它会跳过一行然后再输入。有人知道在 Java 中获取句子输入的另一种方法吗?
输入示例:
2
geeksforgeeks
geeks for geeks
期望输出:
geeksforgeeks
代码:
class GFG {
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int testcases=sc.nextInt();
while(testcases--!=0)
{
String str=sc.nextLine();
System.out.println(str);
}
//code
}
}
英文:
Whenever I use sc.nextLine in java I get this error. It skips one line. Anybody knows how to fix it. sc.nextLine fails for multiple test cases as takes skips one line and then take input. Anybody knows another way to take sentence input in java?
For Input:
2
geeksforgeeks
geeks for geeks
your output is:
geeksforgeeks
Code:
class GFG {
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int testcases=sc.nextInt();
while(testcases--!=0)
{
String str=sc.nextLine();
System.out.println(str);
}
//code
}
}
答案1
得分: 0
你需要在 `int testcases=sc.nextInt();` 之后读取一行,因为从扫描器读取整数不会读取行终止符。
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int testcases=sc.nextInt();
sc.nextLine(); //<--在这里!
while(testcases--!=0)
{
String str=sc.nextLine();
System.out.println(str);
}
}
英文:
you have to read a line after int testcases=sc.nextInt();
because reading the Int from scanner is not reading a line Termination chars....
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int testcases=sc.nextInt();
sc.nextLine(); //<--HERE!
while(testcases--!=0)
{
String str=sc.nextLine();
System.out.println(str);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论