提问者:小点点

限制用户输入十六进制数


基本上,用户需要输入一个十六进制数,然后将其转换为十进制和二进制数。我为十进制和二进制转换创建了两个单独的类,它们工作得很好。我想做的是限制输入数字,使“90”成为最小输入,“FF”成为最大输入。

public static void main(String[] args) {
    ForwardorBack Binary = new ForwardorBack();
    Speed Decimal = new Speed();
    String Hexadecimal = "";
    Scanner input = new Scanner(System.in);
    System.out.println("Enter Hexadecimal Number");
    Hexadecimal = input.nextLine();
    while (Hexadecimal.length() > 2 || Hexadecimal.length() < 2) {
        System.out.println("Error Enter different number:");
        Hexadecimal = input.nextLine();
    }
    Decimal.wheels(Hexadecimal);
    Binary.move(Hexadecimal);
}

共1个答案

匿名用户

这是一个在while循环的头部使用的方法

public static boolean validateInput(String input) {
  if  (input.length != 2) {
       return false;
  }

  //Replace with own conversion if needed
  try {
    int decimal = Integer.parseInt(hex, 16);
    if (decimal >= 90 && decimal <= 255) {
        return true;
    }
  } catch (NumberFormatException e) {
    return false;
  }
}

然后像这样使用它

while(!validateInput(hexadecimal)) {
  System.out.println("Error Enter different number:");
  hexadecimal = input.nextLine();
}