当我调用名为print
的最后一个方法时,它所做的只是打印数组中的全0。不知道如何正确修复它。在我的说明中,其方法为(double[] noGreen, double[] green, double[] diff)
,参数为import java.util.Scanner;
public class lab7{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
run(kb);
}
public static void run(Scanner kb){
double[] a = new double[12];
double[] b = new double[12];
double[] diff = new double[12];
fillArray(kb, a, "Enter the amount for Before going green :");
fillArray(kb, b, "Enter the amount for After going green: ");
getDiff(a, b);
print(a, b, diff);
}
public static int getValidInt(Scanner kb, String month){
while (true) {
System.out.print(month + " --> ");
if (kb.hasNextInt()){
int num = Integer.valueOf(kb.nextLine());
if (num >0){
return num;
}else if(num <=0){
System.out.print(month + " --> ");
num = Integer.valueOf(kb.nextLine());
return num;
}
}
kb.nextLine();
}
}
public static void fillArray(Scanner kb, double[] a, String prompt){
System.out.println(prompt);
System.out.println("You must enter a positive amount for each month.");
String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for (int i = 0; i < month.length; i++){
getValidInt(kb, month[i]);
}
}
public static double[] getDiff(double[] a, double[] b){
double[] diff = new double[12];
for(int i =0; i< a.length; i++){
diff[i] = a[i] - b[i];
}
return diff;
}
public static void dashes(){
for(int i = 1; i <= 40; i++){
System.out.print("-");
}
System.out.println();
}
public static void print(double[] a, double[] b, double[] diff){
System.out.println("Here is the summary of your saving");
System.out.printf("%-11s%9s%10s%10s\n", "Month", "No Green", "Green", "Saving");
dashes();
String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for(int i = 0; i < month.length; i++){
System.out.printf("%-10s%8.2f%10.2f%10.2f\n", month[i], a[i], b[i], diff[i]);
}
dashes();
System.out.println();
}
}
。
如果有人可以告诉我如何解决此问题并解释我做错了,那将是很好的。预先感谢。
{{1}}
答案 0 :(得分:0)
您忘记将方法的返回值分配给变量。这意味着您从未更改a
,b
和diff
。
在run
中,将getDiff
分配给diff
:
double[] diff = getDiff(a, b);
这也意味着您可以在以下几行中删除此声明:
double[] diff = new double[12];
在fillArray
中,将getValidInt
分配给a[i]
:
a[i] = getValidInt(kb, month[i]);
答案 1 :(得分:0)
在您的public static void fillArray(Scanner kb, double[] a, String prompt)
方法中,您要发送一个名为double
的{{1}}数组参数,但是在该方法中您从未使用过该参数。因此,当您使用创建的数组调用该方法时,该数组将永远不会被填充。因此,当您首次创建数组时,数组仍会填充默认值a
也许您必须将此调用double
的值分配给getValidInt(kb, month[i]);
变量
关于您的a
调用,您已调用它,但尚未将其分配给getDiff(a, b)
这样的变量diff