简体   繁体   中英

Exceptions handling Java

I'm learning about exceptions handling and I'm wondering what should I do in the following situation:

I would like my input to be in one line, like: 12 100 (first is a cardId, second the capacity). Part with the catching exceptions works fine (I would like mostly to prevent situations when user would put wrong type of input). Problem is that if the exception is in the first variable, then program leaves empty lines or prints error, because there was still one or more variables in input. That's my code:

    private static void newCard(Scanner in) {
    try{
        String cardId;
        int cardCapacity;
        cardId = in.next();
        cardCapacity = in.nextInt();
    }
    catch(Exception e){
        System.out.println(WRONG_INPUT_TYPE);
    }
}

Could you please give me a hand? Thanks!

What you can do to get your input on one line is the following:

private static void newCard(Scanner in) {
    try {
        String cardId;
        int cardCapacity;
        String[] input = in.next().split(" ");
        cardId = input[0];
        cardCapacity = Integer.parseInt(input[1]);
    } catch(Exception e){
        System.out.println(WRONG_INPUT_TYPE);
    }
}

What this does is it reads out the user input(their full line), then it seperates the fields based on a space resulting in a String array of two elements in your case. Then we can easily reference either element in that array. Afterwards we use Integer.parseInt() to convert the String to an int(as the result we had earlier was a String array, remember?) ;)

One approach : Take input each line and split. Then process each value in a different try-catch block to preserve exception to throw it later as bellow:

Exception inputEx = null;   
try{
    String line = in.nextLine();
    String[] data = line.split("\\s+");
    try{ cardId = data[0]; } catch(Exception e){inputEx = e;}
    try{ cardCapacity = Integer.valueOf(data[1]); } catch(Exception e){inputEx = e;}
    if (inputEx != null) throw inputEx;
}
catch(Exception e){
    System.out.println(WRONG_INPUT_TYPE);
}

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