Making sure user inputs all input before thrwing exception

I am developing code in which i need user must enter all the inputs and compiler should throw exception after taking all inputs and do not close program execution abruptly.

Lets say I have to take 4 num inputs from user and at 2 nd input line user enters char then java should take another two inputs and only after that throw an exception

eg:
1
2
@
4

Number mismatch exception

Reply asap

please reply asap

small note for you compiler is compiling your code and not executing it…

1 Like

What about this?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class TokenizerTest {

    private static final int NUMBERS_TO_READ = 4;

    public static void main(final String[] args) throws IOException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        int cnt = 0;
        outer: while ((line = br.readLine()) != null) {
            final StringTokenizer tok = new StringTokenizer(line);
            while (tok.hasMoreTokens()) {
                final String token = tok.nextToken();
                final Integer n = convertToInteger(token);
                if (n != null) {
                    ++cnt;
                    // you can store the number here too...
                }
                if (cnt == NUMBERS_TO_READ) {
                    break outer;
                }
            }
            if (cnt == NUMBERS_TO_READ) {
                break;
            }
        }
    }

    private static Integer convertToInteger(final String s) {
        try {
            return Integer.parseInt(s);
        } catch (final NumberFormatException nfe) {
            return null;
        }
    }

}

But it’s not throwing exception as you wanted…

@spurekar24 : I might be wrong with my answer (it might give error), but this is what i came up with:-

  1. do all your work in a function.

  2. enclose the input code in try block.

  3. now in the main function call it and there write the catch block there.

  4. you can call again the function inside the catch block and then print the exception.

note: you’ll have to be sure that all the variables/arguments you declare/pass must be used as ‘pass by reference’.

note:and all the variable initialization in the for loop initialization case should be made global.

but again, i haven’t worked this out and it might necessarily not work.
Good Luck !! :slight_smile:

pls dont ask ques related to ongoing contests…@all pls dont reply b4 14 Aug 3:00pm IST!!!

and even if u ask ques…pls show some signs of effort taken by u to handle such cases…!!!

ohkies…sorry!! wasnt aware of this clause!!