限制十六进制数字的用户输入

时间:2018-03-17 21:43:11

标签: java string limit

用户基本上需要输入一个十六进制数字,然后将其转换为十进制和二进制数字。我为十进制和二进制转换创建了两个单独的类,它们完美地工作。我想要做的是限制输入数字,使“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 个答案:

答案 0 :(得分:0)

这是在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();
}