在我使用try catch后如何跳回while循环?

时间:2016-02-17 13:21:58

标签: java try-catch

不是整个程序,但是这个程序的作用是它需要一堆数字并分开偶数和赔率。

     public static void main(String [] args)
    {
        Scanner stdin = new Scanner(System.in);//for user input
        int[] evenNum = new int [100];//Even Array up too 100
        int[] oddNum = new int[100];//Odd Array up too 100
        int evenIndex=0;//even numbers
        int input=0;//user input
        int i=0;//incrementer for arrays
        int k=0; 
        int j=0;

        String name;
        System.out.println("Type In Your Name");//Type in name 
        name = stdin.nextLine();

        try{
   while ((i < oddNum.length && i < evenNum.length) && input != -1)
  //Makes sure no more than 100 numbers can be placed.
        {

            System.out.println(name+" Enter a positive number, Enter -1 For results");
            input= stdin.nextInt();
            oddNum[i]=input;
            i++;//Increments array

            }
            }
        catch(Exception d)
        {
            System.out.println("Only Numbers Please");//Makes sure only numbers can be displayed

        }

我尝试过使用return,但这是一个无效的类型,所以我不能。我们可以使用它们的传递参考吗?

2 个答案:

答案 0 :(得分:1)

try catch放入while循环

while ((i < oddNum.length && i < evenNum.length) && input != -1)
//Makes sure no more than 100 numbers can be placed.
{
    try {
        System.out.println(name+" Enter a positive number, Enter -1 For results");
        input= stdin.nextInt();
        oddNum[i]=input;
        i++;//Increments array
    }
    catch(Exception d)
    {
        System.out.println("Only Numbers Please");//Makes sure only numbers can be displayed
    }
}

答案 1 :(得分:0)

抓住你真正想要处理它的例外。

考虑你的结构:

try {
  while {
    //...
  }
} catch {
  //...
}

当您在catch块中时,while块已完成。流已退出该块,因此没有返回路径。基本上,循环结束了。

另一方面,考虑一下:

while {
  try {
    //...
  } catch {
    //...
  }
}

在这种情况下,当您退出catch区块时,您仍然在while区块中。所以循环可以继续。

相关问题