简体   繁体   中英

Do-while doesn't loop back

So I'm working on a that involves binary conversion etc. But my problem here is that I can't seem to make the do-while statement in my code to loopback whenever the catch block finishes executing. Here's my code.

System.out.println("This program converts a binary value to its decimal counterpart.\n");
    Scanner input = new Scanner(System.in);
    boolean invalidInput = true;

    do {

        try {
            System.out.print("(>) Enter the value to be converted: ");
            String numberToConvert = input.nextLine();
            long converted = Long.parseLong(numberToConvert, 2);
            System.out.println("(>) Decimal value of " + numberToConvert + " is : " + converted + "\n");
            invalidInput = false;
        } catch (Exception e) {
            System.out.println("(!) Entered value is non binary, please try again.\n");
            input.next();
        }

    } while (invalidInput);

Remove input.next() from catch block and then try :-

    System.out.println("This program converts a binary value to its decimal counterpart.\n");
    Scanner input = new Scanner(System.in);
    boolean invalidInput = true;

    do {

        try {
            System.out.print("(>) Enter the value to be converted: ");
            String numberToConvert = input.nextLine();
            long converted = Long.parseLong(numberToConvert, 2);
            System.out.println("(>) Decimal value of " + numberToConvert + " is : " + converted + "\n");
            invalidInput = false;
        } catch (Exception e) {
            System.out.println("(!) Entered value is non binary, please try again.\n");
        }

    } while (invalidInput);

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