Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我如何让这个程序接受另一个输入?_Java_Try Catch - Fatal编程技术网

Java 我如何让这个程序接受另一个输入?

Java 我如何让这个程序接受另一个输入?,java,try-catch,Java,Try Catch,我在这条线上发表了评论。为什么该行不接受其他输入?然后继续重复,直到输入一个整数 import java.util.*; class ScanNumbers{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int[] NumberEntry = new int[6]; for (int i = 1; i < NumberE

我在这条线上发表了评论。为什么该行不接受其他输入?然后继续重复,直到输入一个整数

import java.util.*;

class ScanNumbers{

   public static void main(String[] args){

      Scanner scan = new Scanner(System.in);

      int[] NumberEntry = new int[6];

         for (int i = 1; i < NumberEntry.length; i++){

            boolean isInteger = false;

            while (!isInteger){

            try {
                System.out.print("Entry " +i + "/5, enter an integer value: ");
                NumberEntry[i] = scan.nextInt();
               isInteger = true;
             }

            catch (Exception e){
               System.out.print("Entry " +i + "/5, Please enter only an integer value: ");
               NumberEntry[i] = scan.nextInt(); //Right here, I would like to ask again, why is this line not doing the job?
            }
         }
      }
         Arrays.sort(NumberEntry);
         System.out.print("The max integer is: " +  + NumberEntry[NumberEntry.length-1]);
   }
}
import java.util.*;
类扫描数{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
int[]numberntry=新的int[6];
for(int i=1;i
我能不能告诉它再试一次

编辑1:哈哈,哦,我的天,谢谢,我已经删除了这行,但是现在输出继续重复“输入1/5,输入一个整数值:”


编辑2:谢谢!现在一切正常

发生的情况是,无效输入被保存在扫描仪中。您必须跳过输入,以便返回接受有效数据。如果不这样做,异常将被反复捕获。还有一种更简单的方法来做你想做的事情。试试这个:

try {
    System.out.print("Entry " +i + "/5, enter an integer value: ");
    NumberEntry[i] = scan.nextInt();
}
catch (Exception e){
    scan.next();
    i--;
    continue;
}

这会跳过不需要的输入。它还会在同一次迭代中重新启动循环。

这类似于我在本论坛中发现的一篇文章,您的数组大小为6,但当前的for循环只需要5个值。数组索引从0开始。可能重复