循环中的Java try-catch语句

时间:2015-04-07 11:26:39

标签: java try-catch

我有这个方法,它工作正常。我需要放一个try / catch语句 如果用户输入字母,该方法可以继续。我不知道在哪里发表声明,似乎到处都是我说错了。有人可以告诉我这个陈述在哪里?

public void myMethod() {

    Scanner in = new Scanner(System.in);
    int array[] = new int[21];
    int number;

    boolean end = false;

    while (!end) {

        System.out.println("Please give an number between 0-20: ");
        number = in.nextInt();

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

            if (i == number) {

                System.out.println(array[number]);
                end = true;
            }
        }
        if (!end) {
            System.out.println("I cant find number " + number
                    + " in the array, please try again ");
        }

    }

 }

3 个答案:

答案 0 :(得分:0)

    System.out.println("Please give an number between 0-20: ");
    try{
        number = in.nextInt();
    }catch(Exception e){
        number = 1; //Put random number of default number here
    }

答案 1 :(得分:0)

public static void main(String[] args) {

    Test test = new Test();
    Scanner in = new Scanner(System.in);
    int array[] = new int[21];  
    int number;
    System.out.println("Please give an number between 0-20: ");
    do{
        try{
            number = Integer.parseInt(in.next());
        }
        catch(Exception e){
            System.out.println("Please give an number between 0-20: ");
            number = -1;
        }
    }
    while(!(number <= 20 && number >=0 ));
    System.out.println(array[number]);
}

答案 2 :(得分:0)

你的for循环我无法解释,你只需要检查0到20之间的值, 当你调用try catch时,你必须在异常后跳过循环

public static void myMethod() {

    Scanner in = new Scanner(System.in);
    int array[] = new int[21];
    int number=0;

    boolean end = false;

    while (!end) {


        System.out.println("Please give an number between 0-20: ");
        //check symbol
        try{
            number = Integer.valueOf(in.next());
        }catch(Exception e)
        {
            System.out.println("It's not a number! ");
            continue; //skip loop
        }

        if((number>=0)&&(number<=20))
        {
              System.out.println(array[number]);
              end=true;
        }
        else
             System.out.println("I cant find number " + number
                        + " in the array, please try again ");

        /* why do you use loop here???
         * u need to check if number between 0-20
        for (int i = 1; i < array.length; i++) {

            if (i == number) {

                System.out.println(array[number]);
                end = true;
            }
        }*/


    }

 }