2012-11-04 54 views
2

這是我迄今爲止所做的程序。我應該要求出納員輸入價格,如果是寵物,我應該要求y或n。然後,如果有5個或更多項目,則應該有方法計算折扣。除了折扣方法的退貨數據外,我擁有的程序正在運行。關於Java和數組在搜索方法和返回數據

的錯誤是68:error; cannot return a value from method whose result type is void.

我很困惑,爲什麼數據無效。如果我拿出return discount;語句,那麼程序編譯沒有錯誤。

import javax.swing.JOptionPane; 

public class Assignment4 
{ 
    public static void main (String[] args) 
    { 
     double[] prices = new double[1000]; 
     boolean[] isPet = new boolean[1000]; 
     double enterPrice = 0; 
     int i = 0; 
     String yesPet = "Y"; 
     int nItems = 0; 
     do 
     { 
      String input = JOptionPane.showInputDialog("Enter the price for the item: "); 
      enterPrice = Integer.parseInt (input); 

      prices[i] = enterPrice; 

      String petOrNo = JOptionPane.showInputDialog("Is this item a pet? Enter Y for pet and N for not pet."); 

      if (petOrNo.equalsIgnoreCase(yesPet)) 
      { 
       isPet[i] = true; 
      } 
      else 
      { 
       isPet[i] = false; 
      } 
      i = i+1; 
      nItems = nItems + 1; 
     } while (enterPrice != -1); 
     //System.out.println(nItems); 
    } 

    public static void discount(double[] prices, boolean[] isPet, int nItems) 
    { 
     boolean found = false; 
     double[] discount = new double[nItems]; 

     if (nItems > 6) 
     { 
      for (int i = 0; i < nItems; i++) 
      { 
       if (isPet[i] = true) 
       { 
        found = true; 
        break; 
       } 
      } 

      if (found = true) 
      { 
       for (int x = 0; x < nItems; x++) 
       { 
        if (isPet[x] = false) 
        { 
         int n = 0; 
         prices[x] = discount[n]; 
         n = n + 1; 
        } 
       } 
      } 
     } 
     return discount; 
    } 
} 

回答

2

discount方法需要返回一個double陣列。改變

public static void discount(double[] prices, boolean[] isPet, int nItems) { 

public static double[] discount(double[] prices, boolean[] isPet, int nItems) { 

沒有值被分配給任何條目中discount陣列所以每值將是0.0

+0

ty這麼多嘗試過,它的工作...誰讓我做程序的人告訴我所需要的方法是公共靜態無效折扣...所以這是給出 – user1797373

1
public static void discount(double[] prices, boolean[] isPet, int nItems) 

應改爲:

public static double[] discount(double[] prices, boolean[] isPet, int nItems) 

順便說一句,discount從未填補,它會返回一個空數組。

0

方法簽名是您和Java之間的編譯時承諾 - 您承諾返回您指定的類型。 void在方法簽名意味着你不會返回任何東西,但你返回的東西。這違反了承諾,因此是錯誤。

您必須更改方法簽名才能返回double[]以履行對編譯器的承諾。

也是這樣的情況,即discount實際上從來沒有填充 ...分配是從右到左關聯。所以,聲明prices[x] = discount[n]可能不會達到您的預期。

+0

你能指出我可以在哪裏讀取更多關於如何做價格[x] =折扣[n]聲明並使其按照我希望的方式工作? – user1797373

+0

我剛剛意識到你在說什麼......一直在想它錯誤的方式..謝謝你指出了。 – user1797373