首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >限制用户输入十六进制数

限制用户输入十六进制数
EN

Stack Overflow用户
提问于 2018-03-18 05:43:11
回答 1查看 406关注 0票数 0

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

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-18 06:38:06

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

代码语言:javascript
复制
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;
  }
}

然后像这样使用它

代码语言:javascript
复制
while(!validateInput(hexadecimal)) {
  System.out.println("Error Enter different number:");
  hexadecimal = input.nextLine();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49342191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档