現在我正在開發一個GUI,它將根據用戶輸入文本字段的內容計算運動學值。我創建了一個類型爲Double(不是double)的私有內部類,然後創建了一個方法來根據給定的值獲取值。例如,這返回初始速度:試圖用Double和Double計算用戶輸入
public Double getInitialVelocity(Double vf, Double a, Double ti, Double tf) {
deltaT = deltaT(tf, ti);
initialVelocity = vf - (a * deltaT);
df.format(initialVelocity);
return initialVelocity;
}
當我嘗試測試此方法時出現問題。我設置了新的雙打,在我的主類使用getInitialVelocity
:
Kinematics test = new Kinematics(); // creates object from inner class
Double vf = 1.0, a = 2.0, ti = 0.5, tf = 1.5;
test.getInitialVelocity(vf, a, ti, tf);
當我運行這個測試,我得到這個錯誤:
Static Error: No method in Kinematics with name 'getInitialVelocity' matches this invocation
Arguments: (Double, Double, Double, Double)
Candidate signatures: double getInitialVelocity()
有誰知道如何正確地做到這一點?我需要使用Double類型,因爲我比較了賦給null的值,然後使用基於哪些值爲null的適當公式。另外,從字符串轉換時,我應該只使用Double.parseDouble(textField.getText());
?
編輯1:這裏是我的類的相關部分:
私有內部類(運動學):
private class Kinematics {
private Double initialVelocity, finalVelocity, acceleration, timeFinal, timeInitial;
private Double deltaT;
// constructor
public Kinematics() {
}
public Double deltaT(Double tf, Double ti) {
if(!(tf == null && ti == null)){
deltaT = tf - ti;
} return deltaT;
}
public Double getInitialVelocity(Double vf, Double a, Double ti, Double tf) {
deltaT = deltaT(tf, ti);
initialVelocity = vf - (a * deltaT);
df.format(initialVelocity);
return initialVelocity;
}
在我的主類(KinematicsPanel),我有:
Kinematics values = new Kinematics();
viLabel = new JLabel("Initial Velocity: ");
viText = new JTextField(1);
vfLabel = new JLabel("Final Velocity: ");
vfText = new JTextField(1);
aLabel = new JLabel("Acceleration: ");
aText = new JTextField(1);
tiLabel = new JLabel("Initial Time: ");
tiText = new JTextField(1);
tfLabel = new JLabel("Final Time: ");
tfText = new JTextField(1);
// compute button & result
compute = new JButton("Compute");
compute.addActionListener(this);
result = new JTextField(2);
result.setEditable(false); // can not be edited
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
// parse each string to a value
Double vf = 0.0, a = 0.0, ti = 0.0, tf = 0.0;
if(vfText != null) {vf = Double.parseDouble(vfText.getText());}
if(aText != null) {a = Double.parseDouble(aText.getText());}
if(tiText != null) {ti = Double.parseDouble(tiText.getText());}
if(tfText != null) {tf = Double.parseDouble(tfText.getText());}
if(action.equals("Compute")) {
if(viText == null) { // get initial velocity
// get values
values.getInitialVelocity(vf, a, ti, tf);
System.out.println(values.toString()); // to test
result.setText(values.toString());
}
}
作爲權現在,這沒有做什麼,這就是爲什麼我在Dr.Java的交互窗格中測試了這個方法的原因。
EDIT2:正在使用的格式功能在主類:
DecimalFormat df = new DecimalFormat("#.00");
你可以發佈你的全班? – Luke
'getInitialVelocity()'方法中的'initialVelocity'是否是double? –
你會發布'格式'功能 – Scott