问题描述
- 这个要怎么改才能在输入的数不是二进制字符的时候提示输入错误呢
-
比如我输入99 或者abc都提示 Not a binaryimport java.util.Scanner;
public class Binary {public static int toDecimal(String b) { int decimal = Integer.parseInt(b,2); return decimal; } public static boolean isBinary(String b) { int inputNum = Integer.parseInt(b); while(inputNum != 0){ if(inputNum % 10 > 1){ return false; } inputNum = inputNum / 10; } return true; } public static void main(String[] args) { System.out.print("Enter binary: "); Scanner in = new Scanner(System.in); String binaryNum = in.next(); isBinary(binaryNum); int outputDecimal = toDecimal(binaryNum); System.out.print("n"+ outputDecimal +" in decimal"); }
}
解决方案
就是在你调用isBinary后添加一句判断语句就可以了啊。
boolean isBinary = isBinary(binaryNum);
if(isBinary){
System.out.print("n" + binaryNum + "is Binary");
}else{
System.out.print("n" + binaryNum + "is not Binary.");
}
时间: 2024-10-22 16:51:27