2012-08-14 153 views
0

這是主類從方法返回數組

actionsClass actionObject = new actionsClass(tipArray, hourArray, 
    hourlyWageInput, gasArray, wageArray, incomeArray, totalHourlyEarnings, 
    totalGas, totalHours, avgGasLabel); 

actionObject.calculateTable(); 

這是我的課,我想實現的方法(目前有過度聲明的變量):

import javax.swing.JButton; 
import javax.swing.JLabel; 
import javax.swing.JTextField; 

public class actionsClass { 

private JLabel hourlyWage, blank, row2, totalTips, totalHours, totalHourlyEarnings, 
totalPay, weekPay, day, totalGas, totalHoursLabel, totalTipsLabel, totalGasLabel, 
totalWageLabel, avgGas, avgGasLabel; 
private JTextField hourlyWageInput; 

private double incomeArray[] = new double[7]; 
private JTextField tipArray[] = new JTextField[7]; 
private JTextField hourArray[] = new JTextField[7]; 
private JTextField gasArray[]= new JTextField[7]; 
private JLabel wageArray[] =new JLabel[7]; 


public actionsClass() { 
} 

public actionsClass(JTextField[] tipArray, JTextField[] hourArray, 
     JTextField hourlyWageInput, JTextField[] gasArray, 
     JLabel[] wageArray, double[] incomeArray, 
     JLabel totalHourlyEarnings, JLabel totalGas, JLabel totalHours, 
     JLabel avgGasLabel) { 
    this.tipArray = tipArray; 
    this.hourArray = hourArray; 
    this.hourlyWageInput = hourlyWageInput; 
    this.gasArray = gasArray; 
    this.wageArray = wageArray; 
    this.incomeArray = incomeArray; 
    this.totalHourlyEarnings = totalHourlyEarnings; 
    this.totalGas = totalGas; 
    this.totalHours = totalHours; 
    this.avgGasLabel = avgGasLabel; 
} 

public String calculateTable(){ 
    for (int i = 0; i < 7; i++) { 
     double tipx = Double.parseDouble(tipArray[i].getText()); 
     double houry = Double.parseDouble(hourArray[i].getText()); 
     double hourlyz = Double.parseDouble(hourlyWageInput.getText()); 

     String[] wageArrayStrings = null; 

     if (houry != 0){ 
      wageArrayStrings[i] = String.format("%.2f", (hourlyz*houry+tipx)/houry); 

     } 
     else { 
      wageArrayStrings[i] = ("$ 0.00"); 
     } 

    } 
    return wageArrayStrings[]; 
} 

}

有在返回wageArrayStrings一個語法錯誤[];帶或不帶括號。我究竟做錯了什麼?

回答

2

首先,返回類型應該是String[]

然後,你需要初始化數組(如@MattBall指出,在循環之前):

String[] wageArrayStrings = new String[7]; 
for (int i = 0; i < 7; i++) { 

然後,你可以做

return wageArrayStrings; 
+3

N.B.該數組應該在循環之外聲明並初始化。 – 2012-08-14 00:22:58

+0

這是我看到的主要問題。謝謝你們倆! – 2012-08-14 00:24:22

0

應該只返回wageArrayStrings;不需要方括號和返回類型應該是String[]而不是String(假設你的意圖是返回String數組)。

0

應該僅僅是(改變函數的返回類型太) -

public String[] calculateTable() { 

    //// your code. 
    return wageArrayStrings; 
} 

另外,你還沒有初始化你的數組。你應該在for循環之前做到這一點。