用户在Java中输入的句子。

huangapple go评论61阅读模式
英文:

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);
    }

huangapple
  • 本文由 发表于 2020年9月22日 14:48:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64004428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定