简体   繁体   English

Do-while 不会循环返回

[英]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.所以我正在研究一个涉及二进制转换等的问题。但我的问题是,每当 catch 块完成执行时,我似乎无法使代码中的 do-while 语句循环回送。 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 :-从 catch 块中删除 input.next() 然后尝试:-

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM