简体   繁体   中英

Try/ Catch problems when using For loop in Java

I was trying to get 10 Integer input from users. In addition, I want to handle the exception when users enter the wrong type of data (not Integer). However, I have this problem when using the for loop & try/catch together. For example, if I enter String at the 4th number. I would get this as a result:

Type 1. integer: 15
Type 2. integer: 152 
Type 3. integer: 992
Type 4. integer: jj
Invalid number
Type 5. integer: Invalid number
Type 6. integer: Invalid number
Type 7. integer: Invalid number
Type 8. integer: Invalid number
Type 9. integer: Invalid number
Type 10. integer: Invalid number

Integers: [15, 152, 992]

I don't know how to reenter the loop after the exception is caught.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);
    Integer integer;
    List<Integer> integerList = new ArrayList<Integer>();
    for (int i = 1; i < 11; i ++) {
        System.out.print("Type " + i + ". integer: ");
        try {
        integer = input.nextInt();
        integerList.add(integer);
        }
        catch (InputMismatchException exc) {
            System.out.println("Invalid number");
        }

    }
    System.out.println("Integers: " + integerList);
}

you don't leave the for-loop on exception. instead of a for-loop, i'd recommend a while-loop, eg

//  your code
while (integerList.size() < 10) {
    Scanner input = new Scanner(System.in);
    //  your code
    try {
    //  your code
    }
    catch (InputMismatchException exc) {
        input.nextLine();
        //  your code
    }
    //  your code
}
//  your code

Or decrease the counter when ever exception count so that cycle won't be count.

 catch (InputMismatchException exc) {
            System.out.println("Invalid number");
            i--;       
}

You have to clear the Scanner input:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.InputMismatchException;

class foo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        Integer integer;
        List<Integer> integerList = new ArrayList<Integer>();
        for (int i = 1; i < 11; i ++) {
            System.out.print("Type " + i + ". integer: ");
            try {
                integer = input.nextInt();
                integerList.add(integer);
            }
            catch (InputMismatchException exc) {
                System.out.println("Invalid number");
                input.nextLine();
                --i;
            }
        }
        System.out.println("Integers: " + integerList);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM