Java 将字符串读入int数组

Java 将字符串读入int数组,java,arrays,int,Java,Arrays,Int,我希望扫描器读取带有数字和空格的输入,并将其放入int数组中,我的代码如下,但即使输入有效输入,如“5 3 4”,我仍会收到“您必须至少指定一个转子”。我很抱歉,如果代码混乱或不是我所需要的 String rotorConfiguration = scnr.nextLine(); Scanner readRotorConfig = new Scanner(rotorConfiguration); int [] intRotorConfig = new int[rotorConfiguratio

我希望扫描器读取带有数字和空格的输入,并将其放入int数组中,我的代码如下,但即使输入有效输入,如“5 3 4”,我仍会收到“您必须至少指定一个转子”。我很抱歉,如果代码混乱或不是我所需要的

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);
    }
}
String-rotorConfiguration=scnr.nextLine();
扫描仪readRotorConfig=新扫描仪(转子配置);
int[]intRotorConfig=new int[rotorConfiguration.length()];
对于(int i=0;i如果(testRotorConfig>=0&&testRotorConfigfor循环中的条件是错误的。您正在迭代名为rotorConfiguration的字符串(包括空格)的长度。我想您的意思是迭代字符串中的标记

while(readRotorConfig.hasNextInt(){
  int rotorConfig = readRotorConfig.nextInt();

  //more operations here
}
一件事

int [] intRotorConfig = new int[rotorConfiguration.length()];
您必须在
[]
内指定3,但在该行指定5。(正如您提到的长度,您应该测量数字)

要更正它,请找到空格的频率,然后设置如下:

int [] intRotorConfig = new int[freq + 1];

您正在执行+1,因为空间数量将减少

您是否在调试器中逐步完成了代码?通过这种方式,您可以检查变量的值,以了解为什么条件按您希望的方式计算。您是否可以在调试模式下运行此代码,以查看
rotorConfiguration
的值。您还应该循环中的断点,用于查看每次求值期间
testRotorConfig
的值。您还应该包括处理下一个标记不是
int
的情况的逻辑。您还始终希望将
hasNext..()
调用与等效的
next…()
调用配对-使用
hasNext()
并调用
nextInt()
将导致您通常不想要的行为。OP需要一个
i
tooI假设OP是;控制他的输入,并理解在未知输入上使用nextInt的后果。答案是为了说明解决方案,而不是作为健壮的代码体。