将字符串读入int数组

时间:2015-03-04 00:20:03

标签: java arrays int

我希望扫描程序读取带有数字和空格的输入并将其放入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);
    }
}

2 个答案:

答案 0 :(得分:0)

for循环中的条件错误。您正在迭代称为rotorConfiguration的字符串(包括空格)的长度。我认为你的意思是迭代字符串中的标记。

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

  //more operations here
}

答案 1 :(得分:0)

一件事

int [] intRotorConfig = new int[rotorConfiguration.length()];

您必须在[ ]内指定3,但在该行中指定5。 (因为你提到长度,你应该测量数字)。

为了纠正它,找到空间的频率然后设置如下:

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

你正在做+ 1,因为没有。空间将更少