在使用Java的nextInt()方法时,我遇到了这段代码:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
String string1 = scan.nextLine();
我知道 string1 将包含一个空字符串。我的问题是为什么像下面这样调用 nextLine 方法两次会出现错误:
String string1 = scan.nextLine().nextLine();
最佳答案
这里:
String string1 = scan.nextLine().nextLine();
让我们分解一下:
String string1 = scan.nextLine()
在扫描仪上调用nextLine()
。它返回一个字符串。
因此,您的代码可以归结为
String string1 = someOtherString.nextLine();
这当然是行不通的。因为 String 类不知道下一行,因此没有这样的方法!
记住:扫描仪返回一个字符串,这是两个非常不同的对象。
如果你从盒子里取出一个鸡蛋,为什么你会期望你能从你得到的鸡蛋中取出另一个鸡蛋?!你可以从同一个盒子里取出两个鸡蛋,但不能从一个鸡蛋里取出一个鸡蛋。
最后:是的,有“流畅”API 的想法,它允许以“这样”的方式链接方法调用。但这只能只适用于专门为此设计的场景。
关于java - 为什么我不能在java中调用nextLine()方法两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260782/