我是Java的新手,正在尝试为复利计算器制作一个基本的GUI。我设置字符串来接收用户输入,它适用于前两个双精度,但是当我希望String为for循环的长度输入时,我得到一个错误。我想做的不可能吗?
import javax.swing.JOptionPane;
class Sample {
public static void main(String[] args) {
String p = JOptionPane.showInputDialog("Enter initial investment: ");
String r = JOptionPane.showInputDialog("Enter interest rate (as a decimal): ");
String y = JOptionPane.showInputDialog("Enter time period (in years): ");
double num1 = Integer.parseInt(p);
double num2 = Integer.parseInt(r);
double num3 = Integer.parseInt(y);
double amount;
for(double year = 1; year <= y; year++){
amount = num1 * Math.pow(1 + num2, year);
}
JOptionPane.showMessageDialog(null, "The answer is: " + amount, "the title", JOptionPane.PLAIN_MESSAGE);
}
}
答案 0 :(得分:0)
你不能使用双重字符串。
那样做:
for(double year = 1; year <= num3 ; year++){
amount = num1 * Math.pow(1 + num2, year);
}
除了在使用之前必须初始化数量,否则它不会被编译。
所以替换:
double amount;
通过
double amount=0;
编辑回答OP的评论。
如果要为年份提供浮动值,则应在进入循环之前将此值舍入为上限值,并在循环的退出条件中使用它。
String y = JOptionPane.showInputDialog("Enter time period (in years): ");
...
double year = Double.parseDouble(y);
在循环之前和循环中你应该:
double iteration = Math.ceil(num3);
for(double year = 1; year <= iteration; year++){
amount = num1 * Math.pow(1 + num2, year);
}
例如,如果您为年份输入输入0.4
,则会转到1.0
,因此您循环一次。
答案 1 :(得分:0)
这应该有效:
String p = JOptionPane.showInputDialog("Enter initial investment: ");
String r = JOptionPane.showInputDialog("Enter interest rate (as a decimal): ");
String y = JOptionPane.showInputDialog("Enter time period (in years): ");
double num1 = Double.parseDouble(p);
double num2 = Double.parseDouble(r);
double num3 = Double.parseDouble(y);
double amount = 0;
for(double year = 1; year <= num3; year++){
amount = num1 * Math.pow(1 + num2, year);
}
JOptionPane.showMessageDialog(null, "The answer is: " + amount, "the title", JOptionPane.PLAIN_MESSAGE);
如果你想要一个double,请不要使用Integer.parseInt()。你也不能将for / loop中的双/整数与字符串进行比较