我对 Java 很陌生,正在尝试为复利计算器制作一个基本的 GUI。我设置字符串来接收用户输入,并且它适用于前两个 double ,但是当我希望字符串接受 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);
}
}
最佳答案
有了这个它应该可以工作:
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()。另外,您不能将 double /整数与 for 循环中的字符串进行比较
关于java - for 循环中的输入对话不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219546/