Java 中用户输入的句子

User Input of sentence in Java

每当我在 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);
    }