【发布时间】:2015-03-04 00:20:03
【问题描述】:
我希望扫描仪读取带有数字和空格的输入并将其放入 int 数组中,我的代码如下,但即使我输入有效输入,例如“5 3 4”,我仍然会收到“you必须指定至少一个转子”。如果代码混乱或不完全符合我的需要,我是一个初学者,非常抱歉。
String rotorConfiguration = scnr.nextLine();
Scanner readRotorConfig = new Scanner(rotorConfiguration);
int [] intRotorConfig = new int[rotorConfiguration.length()];
for (int i = 0; i < rotorConfiguration.length(); i++){
if (readRotorConfig.hasNextInt()){
int testRotorConfig = readRotorConfig.nextInt();
if (testRotorConfig >= 0 && testRotorConfig <= 8){
intRotorConfig [i] = testRotorConfig;
}else{
System.out.println("Invalid rotor. You must enter and integer"
+ " between 0 and 7");
System.exit(-1);
}
}else{
System.out.println("You must specify at least one rotor");
System.exit(-1);
}
}
【问题讨论】:
-
您是否在调试器中单步执行过代码?通过这种方式,您可以检查变量的值,以了解为什么条件正在/未按照您想要的方式进行评估。
-
能否请您在调试模式下运行这段代码,看看
rotorConfiguration的值是多少。您还应该在循环中放置一个断点,以查看每次评估期间testRotorConfig的值。