1. 程式人生 > >利用巢狀的try-catch來將輸入的整數轉換為二進位制數

利用巢狀的try-catch來將輸入的整數轉換為二進位制數


class hello {
	public static void main(String[] args) throws ParseException {
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("輸入一個整數:");
			String s = sc.nextLine();
			try {
				int i = Integer.parseInt(s);
				System.out.println(Integer.toBinaryString(i));
				break;
			} catch (Exception e) {
				try {
					new BigDecimal(s);
					System.out.println("您輸入的是一個小數,請重新輸入");
				} catch (Exception e1) {
					System.out.println("非法字元,請重新輸入");
				}
			}
		}

	}

執行結果: