[英]Try-Catch option does not run in Java
我試圖用Java編寫一個十進制和二進制轉換器。 我正在嘗試使用try&catch選項進行錯誤處理。 例如,如果任何一個輸入“ a”為二進制數,它將打印“錯誤的輸入”。 我已經為此功能使用了parse和try-catch。 但這是行不通的。 我試圖找出問題所在,但未能找到問題。 有人可以幫我這個代碼嗎? 當我寫“ 1”進行二進制到十進制的轉換時,它將到達代碼的末尾。 整個代碼在這里:
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;
}
}
}
scan.nextLine()
應該是scan.next()
nextLine()
不等待用戶輸入,而是讀取剩余的緩沖區,直到下一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.