1

I'm wondering if it's possible to create method for exception handling like this:

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        do {
            try {
                double a = in.nextDouble();
                double b = in.nextDouble();
                double c = in.nextDouble();

                // some code that works with a, b and c variables
            }
            catch(java.util.InputMismatchException exc) {
                System.out.println("Wrong input.");
                in.next();
            }
        } while(true);
    }

So I can input some variables from keyboard, if it's not double, then it says "Wrong input." and wants you to type again. Is it possible to create method that will handle all of this? Is it even possible in Java to create method that can work like this:

double a, b, c;
myMethodTest(a);

and would actually work in the same way as the first code? How to do that, if possible? I know that there is an error that says "variable may not have been initialized", but is there a way to work around it? Can method initialize the variable that I put in (), like myMethodTest(a) could possibly initialize a and do all the exception handling for me?

Colinovsky
  • 38
  • 6
  • Probably `a = myMethodTest(in);` - you don't want to keep opening the Scanner, and check the immutability of primitives – Scary Wombat Mar 16 '20 at 07:43
  • sure, why wouldn't that be possible? – Stultuske Mar 16 '20 at 07:44
  • @Stultuske Because primitives are immutable – Scary Wombat Mar 16 '20 at 07:48
  • @ScaryWombat okay, so if `a = myMethodTest(in)` then how would look this method like? I guess it should be void, but not sure what should be in `()`? – Colinovsky Mar 16 '20 at 07:50
  • @ScaryWombat yes, I know that, but it is possible to put all the business logic of reading the value in a separate method – Stultuske Mar 16 '20 at 07:53
  • @Stultuske could you please give me some example? I'm unable to handle this kind of problem, example would help me a lot. – Colinovsky Mar 16 '20 at 07:54
  • well if you are assigning the return value to `a`, then it can not be void. Also, from your code, I think you can figure out what `in` is. – Scary Wombat Mar 16 '20 at 07:56
  • @Stultuske I knew you knew that I knew. – Scary Wombat Mar 16 '20 at 07:56
  • 1
    @ScaryWombat figured out, it looks like `public static double czyDouble(Scanner in)` and it's working, but I would like to show the whole method code - https://pastebin.com/zQ6UpBJQ could you please check if it's correct? Not sure if it's good to go or maybe there are problems that I cannot see because I'm newbie. By the way, thank you very much for help, your last comment motivated me to try again. Also, some guy in answers did it with void - haven't checked because I was trying this code that I posted above, but it looks like it won't work because it's not double? – Colinovsky Mar 16 '20 at 08:19
  • Not quite, `in = new Scanner(System.in);` is not necessary as you are passing this as a paramater. Also move your existing looping into this methods. You definately do not need the `if` inside the `while`. Also `check` is not needed or used. – Scary Wombat Mar 16 '20 at 08:23
  • @ScaryWombat I forgot to delete those `check` things, was trying some code that I found in google and thought it's not necessary. Now it looks like this https://pastebin.com/Zqy81vTD. Looks a lot better to me, could you please check? – Colinovsky Mar 16 '20 at 08:28
  • Nah, see @Arvind answer below – Scary Wombat Mar 16 '20 at 08:33

2 Answers2

2

Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] argv) {
        Scanner in = new Scanner(System.in);
        double a, b, c;
        a = getDouble(in, "Enter the value of a: ");
        b = getDouble(in, "Enter the value of b: ");
        c = getDouble(in, "Enter the value of c: ");
        System.out.println(a + ", " + b + ", " + c);
    }

    static double getDouble(Scanner in, String inputMessage) {
        double n = 0;
        boolean valid = true;
        do {
            valid = true;
            System.out.print(inputMessage);
            try {
                n = Double.parseDouble(in.nextLine());
            } catch (NullPointerException | NumberFormatException e) {
                System.out.println("Invalid input. Try again");
                valid = false;
            }
        } while (!valid);
        return n;
    }
}

A sample run:

Enter the value of a: a
Invalid input. Try again
Enter the value of a: abc
Invalid input. Try again
Enter the value of a: 10
Enter the value of b: 10.5
Enter the value of c: hello
Invalid input. Try again
Enter the value of c: 20
10.0, 10.5, 20.0
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • Works well, thanks. But have some questions, as I'm a newbie. Instead all of try and catch, isn't `while(!in.hasNextDouble())` enough? I did it this way https://pastebin.com/Zqy81vTD, is your code better in some way? I would like to know if that's better way, maybe my code would not work in some cases? – Colinovsky Mar 16 '20 at 08:40
  • You are most welcome. You should prefer `Scanner::nextLine` to `Scanner::next`, `Scanner::nextDouble` etc. Check [this](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) for a good explanation. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash Mar 16 '20 at 10:30
0

You can check like hasNextDouble() for valid double I have sample code for you below you can modify that according to your need-

 public static void onlyDouble() {

    double myDouble = 0;
    System.out.println(" Please enter Double");
    do {
        while (! in.hasNextDouble()){
            System.out.println(" Please enter valid Double :");
            in.next();
        }
        myDouble = in.nextDouble();
    }while (myDouble  <= 0);

}

Hope this will help you.

Dipankar Baghel
  • 1,596
  • 1
  • 9
  • 21
  • Thanks. Just wondering, is using `try` and `catch` better than `while(! in.hasNextDouble())` in that case? Is there any major difference? – Colinovsky Mar 16 '20 at 08:50
  • @Colinovsky Answer would be in this link just give a look - https://stackoverflow.com/questions/8621762/java-if-vs-try-catch-overhead – Dipankar Baghel Mar 16 '20 at 08:53