2015-04-25 29 views
0

我正在嘗試從單獨的數組中取值並執行分數運算。我創建了一種執行除法的方法,但我一直得到「壞操作數...」的錯誤。我已搜索和搜索,但無法找到解決方案。我需要能夠從tripMiles中獲取數值,並將其除以加侖數。通過單獨數組中的值對一個數組中的值進行劃分

import java.util.Scanner; 

public class Week6Challenge {  
    public static void main(String[] args) { 
     Scanner scan = new Scanner (System.in); 
     int count = 0; 
     //double miles = 0, gallons = 0; 
     //Arrays 
     String[] tripName; 
     tripName = new String[11]; 
     double[] tripMiles; 
     tripMiles = new double[11]; 
     double[] tripMPG; 
     tripMPG = new double [11]; 
     double[] gallons; 
     gallons = new double [11]; 

     //double miles = 0, gallons = 0; 

     while (count <= 9){//start while 
      System.out.println("Enter a description of this trip"); 
      tripName[count] = scan.next(); 

      System.out.println("How many miles did you drive?"); 
      tripMiles[count] = scan.nextDouble(); 

      System.out.println("How many gallons of gas did you use on this trip"); 
      gallons[count] = scan.nextDouble(); 
      count++; 
     }//end while 

     tripMPG[count] = answer(tripMiles, gallons); 

     System.out.println("Trip Name \t Miles Traveled \t MPG"); 
     int k = 0; 
     for(k = 0; k < 10; k++){ 
      System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]); 
     } 
    } 
    public static double answer(double[] num1, double[] num2){ 
     return (num1/num2); 
    } 
} 
+0

發佈確切完整的錯誤消息,並告訴我們它指的是哪一行,而不是強迫我們猜測。你認爲[2,32]除以[2,2,2]應該做什麼? –

回答

1

您正在試圖分裂兩個數組,如:

return (num1/num2); 

這是無效的。

相反,如果您需要兩個數組的長度或總和然後除,可以總結所有元素,然後將這兩個值相除。

0

不能分割陣列像一個方法,這個(num1/num2)

代碼片段怎麼辦arraya分工

public static double answer(double[] num1, double[] num2){ 
    //assumimg both array is of equal length 
    for (int i=0;i<num1.length;i++){ 
double result = num1[i]/num2[i]; 
} 

    } 
0

正如前面已經提到,你不能分割數組對方,但他們的元素。

更改答案功能,因此,而不是增加一倍需要兩個雙兩個數組並返回結果:

//num1 & num2 are double, not array 
public static double answer(double num1, double num2){ 
    return (num1/num2); 
} 

從while循環之後刪除tripMPG[count] = answer(tripMiles, gallons);,而是在結尾處添加以下行的而右環行之前count++;

tripMPG[count] = answer(tripMiles[count], gallons[count]); 

所以你而應該是這樣的:

while (count <= 9){//start while 
    System.out.println("Enter a description of this trip"); 
    tripName[count] = scan.next(); 

    System.out.println("How many miles did you drive?"); 
    tripMiles[count] = scan.nextDouble(); 

    System.out.println("How many gallons of gas did you use on this trip"); 
    gallons[count] = scan.nextDouble(); 

    tripMPG[count] = answer(tripMiles[count], gallons[count]); 
    count++; 
}//end while 
相關問題