簡體   English   中英

限制用戶輸入的十六進制數字

[英]limiting user input for hexadecimal numbers

基本上,用戶需要輸入一個十六進制數字,然后將其轉換為十進制和二進制數字。 我為十進制和二進制轉換創建了兩個單獨的類,它們可以完美地工作。 我想做的是限制輸入數,使“ 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);
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM