响应之前的程序,只需放置 new Balance();其中 public static void main 是不起作用的,如果没有它,程序会运行,但nerner会打印出用户问题!
import java.io.*;
public class cInterest {
public static void main(String[] args) throws IOException
{
//new balance ;
}
public static double balance(double principal, double rate, double years) throws IOException{
double amount = 0;
String input;
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
System.out.print("How much would you like to take out? ");
input = myInput.readLine ();
principal = Double.parseDouble (input);
System.out.print("Enter the interest rate: ");
input = myInput.readLine ();
rate = Double.parseDouble (input);
for (int i = 1; i < years; i++) {
amount = principal * rate * years;
amount += principal;
}
return amount; //- principal;
}
}
balance
是一个方法,而不是一个类,所以你不能使用new
关键词。你想要call相反,方法如下:
public static void main(String[] args) throws IOException
{
double balance = balance(0.0, 0.0, 1.0); // Awkward hard-coded variables! Ew!
System.out.println(balance);
}
但是,当用户要覆盖这些变量时,为什么要将它们传递给方法呢?你的balance
方法应该只负责计算余额,而不是收集用户输入。您可以在main
method:
public static void main(String[] args) throws IOException
{
// Gather user input.
String input;
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
System.out.print("How much would you like to take out? ");
input = myInput.readLine ();
double principal = Double.parseDouble (input);
System.out.print("Enter the interest rate: ");
input = myInput.readLine ();
double rate = Double.parseDouble (input);
System.out.print("Enter the number of years: ");
input = myInput.readLine ();
double years = Double.parseDouble (input);
// Now do the calculations...
double balance = balance(principal, rate, years); // Much clearer!
System.out.println(balance);
}
public static double balance(double principal, double rate, double years) {
// Calculate the end balance based on the parameters, and return it.
}
更好是将用户输入的收集放入其自己的专用方法中,但我已经远远偏离主题了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)