本文介绍了While 循环确定输入的值是否为双精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个相当大的项目,这只是包含在其中.基本上,我创建了一个获取员工信息的类,我们需要它,以便用户必须输入双倍的工资率.说 8.00.请注意,用户不能添加美元符号,例如 $8.00,否则会提示用户发生错误.然而,当我测试运行代码时,没有使用错误提示,代码只是崩溃.

I'm working on a rather larger project and this is just included in it. Basically I created a class that takes an employee's info, we need to have it so the user must enter in a double for their pay rate. Say 8.00. Note the user CANNOT add in a dollar sign such as $8.00, else it will prompt the user an error has occured. Yet when I test run the code, instead of using the error prompt, the code simply crashes.

public static double getPayRate()
 {
    double payRate;
    System.out.println("Please enter the employee's pay rate (a numeric value): ");
    payRate = console.nextDouble();
    while(console.hasNextDouble())
    {
        System.out.println("An error occured with your input...");
        System.out.println("Please enter the employee's pay rate (a numeric value): ");
        payRate = console.nextDouble();
    }
    return payRate;
 }
}

推荐答案

好的,所以使用您拥有的代码,解决这个问题的方法就是这样..虽然此代码可用于检索 double 值,但不建议在处理金钱时使用 double,有关更多信息,请参阅此帖子.为什么不使用 Double 或 Float 来表示货币?

Okay so using the code you have, a way to go about this is like so..While this code works to retrieve a double value, it is not recommended to use double when dealing with money, refer to this post for more information.Why not use Double or Float to represent currency?

import java.util.Scanner;

public class SOTest {

    public static Scanner console = new Scanner(System.in);

    public static double getPayRate()
     {
        while(true)
        {
            System.out.println("Please enter the employee's pay rate (a numeric value):");
            try {
                return Double.parseDouble(console.nextLine());
            } catch(NumberFormatException ex) {
                System.out.println("An error occured with your input...");
            }
        }
     }

    public static void main(String[] args) {
        System.out.println(getPayRate());
    }
}

这篇关于While 循环确定输入的值是否为双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 07:49
查看更多