问题描述
每当我在java中使用sc.nextLine时,都会出现此错误。跳过一行。任何人都知道如何解决它。 sc.nextLine在多个测试用例中均失败,因为Take跳过了一行,然后接受输入。有人知道用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
}
}
解决方法
您必须在int testcases=sc.nextInt();
之后读取一行,因为从扫描仪读取Int不会读取一行终止符...。
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);
}