我正在尝试将 try-catch 放入过程类型方法中,但我 95% 确定它必须是函数类型。我想要完成的是主要使我的代码更短。我想到的最重要的事情之一是将 try-catch 放入方法并调用该方法。
问题是,它会验证输入是否是整数——它甚至会捕获异常,问题是一旦继续执行程序/计算,它就不会“记住”经过验证的输入。这是我遇到问题的代码部分。
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
这是整个程序:
import java.util.Scanner;
public class ch7exercise1
{
public static double compound(double oA, double cI)
{
return roundCent((oA*(Math.pow((1+(percent(cI))),10))));
}
public static double percent(double interest)
{
return interest/100.0;
}
public static double roundCent(double amount)
{
return ((Math.round(amount*100))/100.0); //100.0 is mandatory.
}
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
@SuppressWarnings("unused")
public static void main(String[] args)
{
boolean f = true;
boolean f2 = true;
double origAmount = 0;
double compInterest = 0;
double total = 0;
Scanner iConsole = new Scanner(System.in);
System.out.println("10 year Compound Interest Claculator\n");
System.out.println("Input amount of money deposited in the bank");
tryCatchNum(origAmount);
System.out.println("Input compouded interest rate. (If the compound interest is 3% input 3)");
tryCatchNum(compInterest);
total = compound(origAmount,compInterest);
System.out.println("$"+total);
}
}