【问题标题】:User Input of sentence in Java [duplicate]Java中句子的用户输入[重复]
【发布时间】:2020-09-22 06:48:53
【问题描述】:

每当我在 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 不是读取 lineTermination 字符... .

标签: java string java.util.scanner


【解决方案1】:

您必须在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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多