Java:验证扫描器输入是整数还是整数分数 [英] Java: verify scanner input is integer or integer fraction

查看:76
本文介绍了Java:验证扫描器输入是整数还是整数分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个分数计算器,用于我正在学习Java的课程。根据项目的限制,我需要验证用户扫描仪输入是正整数还是负整数(a)[无小数点]或正整数或负整数分数(a / b)[再次,没有小数点,b必须是积极的,最多只有一个/]。如果用户输入除可接受输入之外的任何内容,我需要在控制台上提示输入无效。请输入(a)或(a / b)其中a和b是整数,b不是零:。



我尝试过:



Google,正则表达式,正则表达式生成器, String.matches(regex),Pattern.compile。

I am working on a fraction calculator for a course I'm taking on Java. According to the confines of the project, I need to verify user Scanner input is either a positive or negative Integer (a)[no decimal points] or a positive or negative Integer fraction (a/b)[again, no decimal points, b has to be positive and a maximum of one "/"]. If the user inputs anything other than acceptable input, I need to keep prompting them on the console with "Invalid input. Please enter (a) or (a/b) where a and b are Integers and b is not zero: ".

What I have tried:

Google, regex's, regex generators, String.matches("regex"), Pattern.compile.

推荐答案

只需搜索' / '字符然后相应地验证整数。尝试:

Just search for the '/' character and then validate the integers accordingly. Try:
class Valid
{
  public static boolean valid(String input)
  {
    int index = input.indexOf('/'); // search the '/' separator
    if ( index == -1 )
    {
      // there is NO separator, a signed integer is allowed
      try
      {
        Integer.parseInt(input);
      }
      catch( NumberFormatException e )
      {
        return false;
      }
    }
    else
    {
      // there is the separator, just a positive integer divisor is allowed
      int d;
      try
      {
        Integer.parseInt( input.substring(0, index) );
        d = Integer.parseInt( input.substring(index+1));

        if ( d <= 0) return false;
      }
      catch( NumberFormatException e )
      {
        return false;
      }
    }
    return true;
  }

  public static void main( String args[])
  {
    // a little test...
    String arr[] = { "10", "-10", "4/7", "-2/3", "5/-3", "7.5", "12/2/3", "12/0"};
    for (String s : arr)
    {
      System.out.printf("valid(%s) =  %b\n", s, valid(s));
    }
  }
}


这篇关于Java:验证扫描器输入是整数还是整数分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆