英文:
Do-while doesn't loop back
问题
以下是翻译好的代码部分:
System.out.println("此程序将二进制值转换为其十进制对应值。\n");
Scanner input = new Scanner(System.in);
boolean invalidInput = true;
do {
try {
System.out.print("(>)请输入要转换的值:");
String numberToConvert = input.nextLine();
long converted = Long.parseLong(numberToConvert, 2);
System.out.println("(>)" + numberToConvert + " 的十进制值为:" + converted + "\n");
invalidInput = false;
} catch (Exception e) {
System.out.println("(!)输入的值不是二进制,请重试。\n");
input.next();
}
} while (invalidInput);
英文:
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);
答案1
得分: 1
System.out.println("此程序将二进制值转换为其十进制对应值。\n");
Scanner input = new Scanner(System.in);
boolean invalidInput = true;
do {
try {
System.out.print("(>)请输入要转换的值:");
String numberToConvert = input.nextLine();
long converted = Long.parseLong(numberToConvert, 2);
System.out.println("(>)" + numberToConvert + " 的十进制值为:" + converted + "\n");
invalidInput = false;
} catch (Exception e) {
System.out.println("(!)输入的值非二进制,请重试。\n");
}
} 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论