我正在尝试从单独的数组中获取值并执行分区数学运算。我已经创建了一个执行除法的方法,但我一直得到“坏操作数......”错误。我搜索和搜索,但找不到解决方案。我需要能够从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 :(得分:1)
你试图划分两个数组,如:
return (num1/num2);
哪个无效。
相反,如果您需要两个数组的长度或总和然后除以,您可以将所有元素相加,然后除以这两个值。
答案 1 :(得分: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];
}
}
答案 2 :(得分:0)
正如已经提到的,你不能将数组彼此分开,而是将它们的元素分开。
更改你的答案函数,而不是两个double数组,它需要两个double并返回结果:
//num1 & num2 are double, not array
public static double answer(double num1, double num2){
return (num1/num2);
}
在while循环后从右侧删除tripMPG[count] = answer(tripMiles, gallons);
,然后在count++;
之前的while循环结束处添加以下行:
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