有人可以告诉我为什么这段代码不断告诉我数字格式异常而不是在我尝试从二进制数转换为小数时不打印我的错误消息吗?`
public static void readAndConvertBinaryValue()
{
Scanner kbd = new Scanner(System.in);
boolean valid = false;
do
{
System.out.print("\nEnter a binary value containing up to 16"
+ " digits: ");
bAction = kbd.nextLine();
int result = bAction.compareTo(BINARY_NUM);
if (result > 1 || result < -9 || bAction.length() > 16)
{
System.out.print("Error: Invalid binary value."
+ "\nTry again.\nPress Enter to continue ...");
kbd.nextLine();
} else
{
char value;
int charlim = 0;
value = bAction.charAt(charlim);
if (value == '1' || value == '0')
{
binary = Integer.parseInt(bAction, 2);
valid = true;
} else
{
System.out.print("Error: Invalid binary value."
+ "\nTrya again.\nPress Enter to continue ...");
kbd.nextLine();
}
}
} while (!valid);
}
答案 0 :(得分:1)
使用正则表达式:
boolean isABinNumber = bAction.matches("^[01]+$");
匹配在String类中定义,当且仅当字符串与提供的正则表达式匹配时才返回true。上面的正则表达式(^ [01] + $)涵盖从开头(^)到结束($)的所有字符串是一个或多个(+)0或1s&#39; [01]&#39; 。
如果您不熟悉正则表达式,网上有大量信息(例如a tutorial)
答案 1 :(得分:1)
这一切看起来都太复杂了,只需使用Integer.parseInt()并捕获NumberFormatException(如果发生)。然后,您可以检查该值是否在所需范围内。
Scanner kbd = new Scanner(System.in);
System.out.print("\nEnter a binary value containing up to 16" + " digits: ");
String bAction = kbd.nextLine();
try {
int binary = Integer.parseInt(bAction, 2);
if (binary >= (1 << 16)) {
System.err.println("Binary value out of range");
}
} catch (NumberFormatException e) {
System.out.print("Error: Invalid binary value.");
}
答案 2 :(得分:1)
import java.util.Scanner;
import java.util.regex.Pattern;
public class CheckBinary {
public static void main(String[] args) {
String binaryNumber = new Scanner(System.in).nextLine();
String binaryPattern = "(1*0*)*";
if (Pattern.compile(binaryPattern).matcher(binaryNumber).matches()) {
System.out.println("Binary");
} else {
System.out.println("Not Binary");
}
}
}