【问题标题】:Primitive type decimal in Java - User EntryJava中的原始类型十进制 - 用户输入
【发布时间】:2018-03-22 01:33:18
【问题描述】:

我正在做一个练习,用户必须使用 Java 编程语言输入带符号的四位十进制数,例如 +3364-1293+0007 等。

据我所知,Java 不支持原始类型小数。
我的问题是:

  1. 如何输入上述数字?
  2. 如何为上述数字提供 +、- 号?

更新

下面的代码显示了一个 sn-p,它要求用户输入一个有效的数字(无字符) - 一元 + 使用下面的代码不起作用!有办法解决吗?

public int readInt() {
    boolean continueLoop = true;
    int number = 0;
    do {
        try {
            number = input.nextInt();
            continueLoop = false;
        } // end try
        catch (InputMismatchException inputMismatchException) {
            input.nextLine();
            /** discard input so user can try again */
            System.out.printf("Invalid Entry ?: ");
        } // end of catch
    } while (continueLoop); // end of do...while loop

    return number;
} // end of method readInt()

【问题讨论】:

  • 看我的回答。你可以用正则表达式来做到这一点。

标签: java


【解决方案1】:

Java 有 8 种原始(非对象/非引用)类型:

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

如果“十进制”是指“以 10 为底的有符号整数”,那么是的,Java 通过 byteshortintlong 支持这一点。您使用哪一个取决于输入范围,但据我所知,int 是最常见的。

如果“十进制”是指类似于 C# 的 Decimal 类型的“以 10 为基数的带绝对精度的有符号浮点数”,那么不,Java 没有。

如果Scanner.nextInt 像我一样为您抛出错误,那么以下应该可以工作:

/* Create a scanner for the system in. */
Scanner scan = new Scanner(System.in);
/*
 * Create a regex that looks for numbers formatted like:
 * 
 * A an optional '+' sign followed by 1 or more digits; OR A '-'
 * followed by 1 or mored digits.
 * 
 * If you want to make the '+' sign mandatory, remove the question mark.
 */
Pattern p = Pattern.compile("(\\+?(\\d+))|(\\-\\d+)");

/* Get the next token from the input. */
String input = scan.next();
/* Match the input against the regular expression. */
Matcher matcher = p.matcher(input);
/* Does it match the regular expression? */
if (matcher.matches()) {
    /* Declare an integer. */
int i = -1;
/*
 * A regular expression group is defined as follows:
 * 
 * 0 : references the entire regular expression. n, n != 0 :
 * references the specified group, identified by the nth left
 * parenthesis to its matching right parenthesis. In this case there
 * are 3 left parenthesis, so there are 3 more groups besides the 0
 * group:
 * 
 * 1: "(\\+?(\\d+))"; 2: "(\\d+)"; 3: "(\\-\\d+)"
 * 
 * What this next code does is check to see if the positive integer
 * matching capturing group didn't match. If it didn't, then we know
 * that the input matched number 3, which refers to the negative
 * sign, so we parse that group, accordingly.
 */
if (matcher.group(2) == null) {
    i = Integer.parseInt(matcher.group(3));
} else {
    /*
     * Otherwise, the positive group matched, and so we parse the
     * second group, which refers to the postive integer, less its
     * '+' sign.
     */
        i = Integer.parseInt(matcher.group(2));
    }
    System.out.println(i);
} else {
    /* Error handling code here. */
}

或者,您可以这样做:

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    if (input.charAt(0) == '+') {
        input = input.substring(1);
    }
    int i = Integer.parseInt(input);
    System.out.println(i);

如果有的话,基本上只需删除“+”号,然后解析它。如果您要进行编程,学习正则表达式非常有用,这就是我给您的原因。但是如果这是作业,你担心如果你使用超出课程范围的东西会引起老师的怀疑,那么千万不要使用正则表达式的方法。

【讨论】:

  • 感谢 Jared 的帖子-但我根本不理解您上面代码 sn-p 中的模式-我没有使用此代码的编程技能-如果可能的话,您能解释一下您的代码请!
  • 我最近添加了(吨)cmets。他们对你解释得不够清楚吗?
  • 谢谢Jared,我以前没见过你的代码sn-p!!
  • 不客气!如果您愿意,我还添加了另一种方法:)
  • @Jared,这不是作业!我目前基本上是在自己学习Java,如果我遇到我所要求的并希望得到结果的事情!我必须感谢您的帖子以及解决此问题所花费的时间。
【解决方案2】:

使用Scanner:

Scanner scan = new Scanner(System.in);
System.out.print("Enter 3 integer numbers: ");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
System.out.print("You have entered: " + a + " | " + b + " | " + c);

输出:

输入 3 个整数:+3364 -1293 +0007
您已输入:3364 | -1293 | 7


附注:在使用前导 0 和整数(如 0007)时要小心,因为它在 Java 中被解释为八进制数而不是十进制数。所以,010 实际上是十进制的8,而不是10

System.out.print(010);

输出:

8

更新:

请注意,Scanner 要求将符号 +- 粘贴到像 +5432-5432 这样的数字上,而不是像 + 5432- 5432

【讨论】:

  • 请注意,您不能使用Integer.parseInt(),因为它不接受一元+Scanner 可以。
  • +123 线程“main”中的异常 java.util.InputMismatchException:对于输入字符串:java.util.Scanner.nextInt 的“+123”(Scanner.java:2097)在 java.util。 Scanner.nextInt(Scanner.java:2050) 在 Main.main(Main.java:6)
  • 感谢 Fouad 的回答 - 但正如 Jared 所说,每次我尝试在数字前面加上 + 时都会收到 inputMismatchException。我不知道如何解决这个问题!!
  • 这似乎很奇怪,因为Scanner 文档告诉它应该很好地解析一元+。语法:Integer :: = ( [-+]? ( Numeral ) )
  • @Alexey - 我试图将 + 号放在数字前面,编译器发出异常 (InputMismatchException)。
【解决方案3】:

您可以使用Scanner 类来读取值。您将需要做更多的工作以确保 + 不是您转换为 Integer 的一部分(检查 Integer 包装类),因为 Scanner 不会接受 + 作为一元运算符(它适用于负数)。

【讨论】:

  • 感谢您的回答 - 我的主要问题是 + 号,我不知道如何克服它并让扫描仪读取它!我遇到的另一个问题是数字前面的前导零!
  • 其实Scanner接受+-,看我的回答。
  • @Eng.Fouad:我刚刚又试了一次(Java 6,请注意),它仍然吐出一个异常。
  • @Eng Fouad,我正在尝试使用下面的代码插入 + - sn-p 显示了 readInt() 方法的示例,我编写该方法仅接受来自用户的整数,如果用户尝试输入无效字符,然后它会一直询问用户,直到它得到一个有效的数字,
  • public int readInt() { boolean continueLoop = true;整数 = 0;做 { 尝试 { number = input.nextInt();继续循环=假; }// 结束尝试 catch (InputMismatchException inputMismatchException) { input.nextLine(); /** 丢弃输入,以便用户可以重试 */ System.out.printf("Invalid Entry ?: "); }// 捕获结束 } while (continueLoop); // do...while 循环结束返回数字; }// 方法 readInt() 结束
【解决方案4】:

看看定点数。 DecimalFormat 类可以为您设置格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 2016-09-21
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2020-06-25
    相关资源
    最近更新 更多