利用嵌套的try-catch来将输入的整数转换为二进制数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40567229/article/details/86000766

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("非法字符,请重新输入");
				}
			}
		}

	}

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_40567229/article/details/86000766