gpt4 book ai didi

java - 在java中获取整数后的输入字符串时出错

转载 作者:行者123 更新时间:2023-12-01 18:12:07 25 4
gpt4 key购买 nike

我正在尝试这样做:

int n = myScanner.nextInt();
for(int i=0;i<n;i++){
String str = myScanner.nextLine();
.
.
.
}

当我编译时,它显示一些错误 java.util.Scanner.nextInt(Scanner.java:2117)。最初我认为这是 nextLine() 的问题,所以我使用了 next() 。然后我发现在 n i.e 中输入输入后是否添加 myScanner.nextLine()

    int n = myScanner.nextInt();
myScanner.nextLine();

然后就一切顺利了。我想知道为什么会发生这种情况?

最佳答案

传递整数时需要消耗输入的换行符:

int n = myScanner.nextInt(); //gets only integers, no newline
myScanner.nextLine(); //reads the newline
String str;
for(int i=0;i<n;i++){
str = myScanner.nextLine(); //reads the next input with newline
.
.
.
}

关于java - 在java中获取整数后的输入字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32197007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com