gpt4 book ai didi

java - 扫描仪问题

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

我的扫描仪和 nextLine 有问题。发生的情况是它跳过了循环的第一圈。我的猜测是扫描仪已经包含了一些东西,比如换行符之类的。如果我对 strCount 和循环中的一个使用两个不同的扫描仪,它确实有效。这是正确的吗?如果是,有什么方法可以在不使用两个不同扫描仪的情况下完成这项工作。

import java.util.*;

public class chars_in_string {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);

System.out.print("Number of strings?");
int strCount = key.nextInt();
String [] array = new String[strCount];

for(int x = 0; x < strCount; x++){

System.out.print("String "+(x+1)+":");
array[x] = key.nextLine();

}
}

}

输入/输出示例:

字符串的数量? 8

字符串1:字符串2:

从这里输入任何字符串都可以正常工作,它只会在循环中跳一步以获取下一个字符串。

最佳答案

问题是 Scanner.nextInt() 不消耗行终止符。只需在进入循环之前执行额外的 nextLine() 即可。

关于java - 扫描仪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709931/

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