如何识别双打和负值

时间:2018-10-14 05:55:39

标签: java

//该程序可以编译并运行以计算平均值,我正努力为它添加负值和双精度值。

import java.util.*;
    public class DoWhileLoops {
        public static void main (String [] args) {
            Scanner kb = new Scanner(System.in);
            int sum = 0,
            ct = 0;
            String input = "";
            do {
                System.out.println
                ("Enter a positive whole number, or q to quit.");
                int n=0, sct=0;
                char c;
                input = kb.nextLine();
                do {
                    c = input.charAt(sct);
                    if (c >= '0' && c <= '9')
                    {
                        n = n * 10;
                        n += (int)(c - '0');
                    }
                    sct++;
                } while (sct < input.length());
                if (n > 0) {
                    sum += n;
                    ct++;
                }
            } while (!input.equalsIgnoreCase("q"));
            System.out.printf("The sum of the %d numbers you entered is: %d\n", ct, sum);
            if(ct > 0)
                System.out.printf("The average is: %.2f", (double)sum/ct);
            else
                System.out.printf("No numbers entered - can't compute average");
        }
    }

//需要帮助该程序,以便它可以识别正负值以及双精度值。

1 个答案:

答案 0 :(得分:0)

您可以在Regular Expression方法中使用String#matches()(正则表达式)来确定用户是否输入了有效数字的字符串表示形式,该数字表示带符号(负)或无符号(正)整数或双精度数据类型值,例如:

if (!input.matches("-?\\d+(\\.\\d+)?")) {
    System.err.println("Invalid numerical value supplied! Try again..." + ls);
    continue;
}

上面的 matches()方法中使用的正则表达式为:"-?\\d+(\\.\\d+)?",这是它的含义的解释:

enter image description here

求和时,要使用双精度数据类型变量,这意味着当用户提供值时,我们希望将其解析为双精度数据类型。为此,您可以使用Double.parseDouble()方法将字符串数字值转换为双精度数据类型,然后将该值添加到我们的求和(我们已经声明为< strong> double )。

代码如下所示:

Scanner kb = new Scanner(System.in);
String ls = System.lineSeparator();
double sum = 0;
int counter = 0;
String input;
do {
    System.out.print((counter + 1) + ") Enter a numerical value (or q to finish): ");
    input = kb.nextLine();
    // If the first character supplied by User is a Q then exit loop
    if (Character.toString(input.charAt(0)).equalsIgnoreCase("q")) {
        break;
    }
    // If the value supplied is not a numerical value
    // then inform User and let him/her/it try again.
    if (!input.matches("-?\\d+(\\.\\d+)?")) {
        System.err.println("Invalid numerical value supplied! Try again..." + ls);
        continue;
    }

    counter++;
    double num = Double.parseDouble(input);
    sum += num;
} while (true);  // q must be given to exit loop.

System.out.printf(ls + "The sum of the %d numbers you entered is: %f\n", counter, sum);
if (counter > 0) {
    System.out.printf("The average is: %.2f", (double) sum / counter);
}
else {
    System.out.printf("No numerical values entered! - Can not compute average!");
}