尝试并抓住一个方法

时间:2012-10-28 22:45:01

标签: java function methods try-catch procedure

我正在尝试将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);


}

}

2 个答案:

答案 0 :(得分:2)

Java参数按值传递。您将0传递给tryCatchNum方法。该值的副本将传递给该方法。此方法为其自己的副本分配新值,然后返回。所以原始值仍为0.

您不得向该方法传递任何内容。相反,该方法必须返回已验证的值。另外,请考虑使用更合适的方法名称:

public double readDoubleValue() {
    ...
    return value;
}

在主要方法中:

double origAmount = readDoubleValue(); 

答案 1 :(得分:0)

由于double是Java中的基元,因此它通过值传递给方法,因此当您更改基元的值时,对方法参数的更改不会反映在传递给方法调用的原始变量中。

阅读Java牧场上的杯子故事,解释通过价值并通过参考传递。 http://www.javaranch.com/campfire/StoryCups.jsp

下一个要阅读的故事是关于Java Ranch的Pass By Value故事。 http://www.javaranch.com/campfire/StoryPassBy.jsp

您应该更改您的方法,以便它返回一个double,它在程序的main方法中赋值。

我也非常好奇你为什么要使用一个检查为true的while循环。我认为如果输入的值无法转换为double,那么您的程序很可能会遇到无限循环。