Java编译报".class" expected错误是什么原因?附完整出错代码
编译错误原因及修复方案
核心错误点
- 方法调用语法不符合规范
Java定义方法时需要标注参数类型,但调用方法时不能加参数类型声明,你写的presentValue(double f, double r ,int n)属于把方法定义的语法套到了调用环节,是触发所有报错的核心原因。
同时你的presentValue方法内部已经通过弹窗获取了三个参数的数值,根本不需要从外部传参,所以方法定义里的参数也可以直接删掉,避免逻辑冗余。 - 存在不可达代码
presentValue方法中return p;执行后会直接结束方法返回结果,后面的System.exit(0);永远不会运行,属于无效代码需要删除。
修复后完整代码
import javax.swing.JOptionPane; /*This program computes a customers present deposit to make to obtain a desired future value */ public class Deposit { //Main method public static void main(String[] args) { //Calling the present value method double results=presentValue(); //Displaying the present value JOptionPane.showMessageDialog(null, "You have to deposit: $" + results); } public static double presentValue() { //Declaring the input variable String input; double f, r; int n; //Taking inputs from the customer //Future value input = JOptionPane.showInputDialog("Enter your desired future value:"); f = Double.parseDouble(input); //Annual Interest Rate input = JOptionPane.showInputDialog("Enter the annual interest rate (e.g. 0.05 for 5%):"); r = Double.parseDouble(input); //Number of years input = JOptionPane.showInputDialog("Enter the number of years:"); n = Integer.parseInt(input); //Calculating the present value the customer has to deposit double p = f / Math.pow((1 + r), n); //Returning the value to the present value method return p; } }
补充说明
如果用户输入利率时习惯填百分比数值(比如输入5代表5%),可以在读取r的代码后加一行r = r / 100;做自动转换,避免计算结果出错。
内容的提问来源于stack exchange,提问作者SABS-TECH
相关产品推荐
相关产品推荐

