检查输入到数组中的输入是否正确/不正确

时间:2015-01-11 14:11:44

标签: java arrays input java.util.scanner

我正在解决一个问题,我必须检查输入到数组中的输入是否介于1和10000之间。如果是,我必须继续进行下一组操作。我该怎么做呢。 请在下面找到我的代码:

Scanner in =  new Scanner(System.in);
    System.out.println("Enter 10 values between 1 and 10000: " );
    for(int i=0; i<10; i++) {
          if (z[i]>1 && z[i]<10000) {
        z[i] = in.nextInt();
        }
    }

但我无法检查&#34; if&#34;声明我已经放在那里。你可以帮帮我吗。

2 个答案:

答案 0 :(得分:3)

首先将输入保存到变量

int num = in.nextInt();

然后验证

if(num>1 && num < 10000) {
   z[i] =num;
}else {
   System.out.printf("Invalid number: %d",num);
}

答案 1 :(得分:0)

你想使用下面的模式行(伪代码,因为像这样的问题通常是家庭作业和基于学习的,没有找到答案和副本)。我想要伟大的未来程序员!

首先是设置:

  1. 将变量初始化为&#34;您应输入的内容&#34;您为用户计划的消息。为什么?所以如果你需要改变它,你只有一个地方可以去!
  2. 将变量初始化为您将检测到的任何错误消息
  3. 建立输入流
  4. 现在循环:

    Issue the "what you should enter" message
    Initialize any needed counters
    begin the loop (while counters < value?)
       // use try catch to surround your input and calculations to catch malformed integers etc
       try {
           get candidate data element from input stream
           check for validity
             if success increment count, do other needed work
             if fail, reissue "what you should enter" message or more specific error message
       } catch malformed input {
             reissue "what you shoue enter" message, including error for malformed input
       }
    end loop
    

    注意,如果您在某些情况发生之前正在工作(例如用户输入QUIT),则使用该条件(第一次设置为false)作为循环终止测试

相关问题