Search code examples
javaparsingerror-handlingtry-catchparseint

Try-Catch option does not run in Java


I am trying to write a Decimal & Binary converter in Java. I am trying to use try & catch option for error handling. Such as, if any one input "a" as binary number, it will print "Wrong Input". I have used parse and try-catch for this function. But it is not working. I am trying to find out the problem, but I am failed to find it. Could anyone help me in this code? When I write "1" for binary to decimal conversion, it goes to the end of the code. The whole code is here:

package binary.with.decimal;

import java.util.Scanner;

public class RiaJava {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int binaryp = 0;
        int n;
        int base = 2;
        int result = 0;
        int multiplier = 1;

        System.out.println("1.Binary to Decimal \n 2.Decimal to Binary");
        System.out.println("Enter Your Option Number:");
        n = scan.nextInt();

        switch (n) {
        case 1:
            System.out.println("Input Binary Number:");

            String binary = scan.nextLine();
            scan.close();
            try {
                binaryp = Integer.parseInt(binary);
            }

            catch (NumberFormatException e) {
                System.out.println("Wrong Input!!!");
            }

            while (binaryp > 0) {
                int residue = binaryp % base;
                binaryp = binaryp / base;
                result = result + residue * multiplier;
                multiplier = multiplier * 10;
            }
            System.out.println("Decimal....." + result);

            break;
        case 2:
            System.out.println("Input Decimal Number:");
            int decimal = scan.nextInt();
            scan.close();

            while (decimal > 0) {
                int residue = decimal % base;
                decimal = decimal / base;
                result = result + residue * multiplier;
                multiplier = multiplier * 10;
            }
            System.out.println("Binary....." + result);
            break;
        default:
            System.out.println("you have selected wrong option number");
            break;
        }
    }
}

Solution

  • scan.nextLine() should be scan.next()

    nextLine() doesn't wait for user input, but reads the remaining buffer until the next end of line.