【发布时间】:2014-06-12 20:23:40
【问题描述】:
我目前正在制作一个应用程序,其中用户输入货币价值,价值的变化是用尽可能少的硬币产生的。我已经使程序正常工作,但我在验证时遇到了问题。为了确保只输入货币值,我尝试捕获以确保不输入任何字母,并使用 if 语句确保仅输入带两位小数的数字。为了尝试使它更整洁,我将它们分成两种不同的方法,在我的 main.js 中执行。
这两种方法都能发挥作用。我遇到的问题是,一旦他们产生消息,即使没有输入适当的货币价值,程序的其余部分仍然运行。我如何做到这一点,以便提示用户输入另一个数字。
所有相关代码如下所示。先感谢您。 这是主要的样子:
public static void main(String[] args ) {
GetValue.AskValue();
GetValue.CheckValue1();
GetValue.CheckValue2();
CalculateChange.Rounding();
CalculateChange.GenerateDollars();
CalculateChange.GenerateHalfDollar();
CalculateChange.GenerateQuarter();
CalculateChange.GenerateDime();
CalculateChange.GeneratePennyX2();
CalculateChange.GeneratePenny();
CalculateChange.GenerateResults();
}
它们位于一个类中:
static void CheckValue1(){
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please input an integer: ");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
number =sc.nextDouble();
} catch(InputMismatchException exception) {
//Print "This is not an integer"
//when user put other than integer
System.out.println(" Please do not type letters");
AskValue();
}
// number = sc.nextDouble();
}
static void CheckValue2(){
String[] splitter = Double.toString(number).split("\\.");
splitter[0].length(); // Before Decimal Count
int decimalLength = splitter[1].length(); // After Decimal Count
if (decimalLength <= 2){
java.math.BigDecimal bd = new java.math.BigDecimal(String.valueOf(number));
Input = Input.add(bd);
} else{
System.out.println(number +" Is not a valid number. You may only go to two decimal palces");
}
}
【问题讨论】:
-
请注意,您的方法名称不符合 Java 标准用法。它们会起作用,但如果你使用 Java 约定,你的代码会更容易阅读。
-
你的代码有问题吗?
-
chrylis 感谢您的评论,我将对其进行更改以遵循命名约定。
标签: java if-statement try-catch