【问题标题】:reading a string into an int array将字符串读入 int 数组
【发布时间】: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 的值。

标签: java arrays int


【解决方案1】:

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

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

  //more operations here
}

【讨论】:

  • 您还应该包括处理下一个令牌不是int的情况的逻辑。
  • 您还总是希望将您的 hasNext..() 呼叫与等效的 next...() 呼叫配对 - 使用 hasNext() 和呼叫 nextInt() 会导致您通常不想要的行为。
  • OP 也需要i
  • 我假设 OP 是;控制他的输入,并了解在未知输入上使用 nextInt 的后果。答案是为了阐明解决方案,而不是成为健壮的代码体。
【解决方案2】:

一件事

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

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

为了纠正它,找到空间的频率,然后像这样设置:

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

你正在做+1,因为没有。空间会更小

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多