У вас должна быть переменная для хранения общей продажи. Кроме того, среднее количество проданных автомобилей в месяц должно быть рассчитано путем деления общего количества на число (количество лет * 6). В дополнение к этому, вы должны следовать Java соглашениям об именах например, класс carwip2
должен быть назван как Carwip2
Сделайте это следующим образом:
import java.util.Scanner;
public class Carwip2 {
public static void main(String args[]) {
getAverageCarSales();
}
public static void getAverageCarSales() {
Scanner sc = new Scanner(System.in);
int total_no_car_sold = 0, no_car_sold = 0, z = 0;
int yr_no = 0;
int yrs = 0;
double average_sold = 0.0;
System.out.print("Enter number of years: ");
yr_no = sc.nextInt();
if (!isValid(yr_no)) {
return;
}
for (int i = 0; i < yr_no; i++) {
System.out.print("Enter the year: ");
yrs = sc.nextInt();
if (!isValid(yrs)) {
return;
}
for (int j = 0; j < 6; j++) {
System.out.print("Enter number of cars sold for year " + yrs + " in month #" + (j + 1) + ": ");
no_car_sold = sc.nextInt();
if (!isValid(no_car_sold)) {
return;
}
total_no_car_sold = total_no_car_sold + no_car_sold;
}
}
System.out.println("Total number of months:" + (yr_no * 6));
System.out.println("Total number of cars sold: " + total_no_car_sold);
average_sold = total_no_car_sold / (yr_no * 6.0);
System.out.println("Average number of cars sold per month: " + average_sold);
}
public static boolean isValid(int x) {
return true;
}
}
Пример прогона:
Enter number of years: 2
Enter the year: 2005
Enter number of cars sold for year 2005 in month #1: 2
Enter number of cars sold for year 2005 in month #2: 3
Enter number of cars sold for year 2005 in month #3: 4
Enter number of cars sold for year 2005 in month #4: 1
Enter number of cars sold for year 2005 in month #5: 2
Enter number of cars sold for year 2005 in month #6: 3
Enter the year: 2006
Enter number of cars sold for year 2006 in month #1: 4
Enter number of cars sold for year 2006 in month #2: 3
Enter number of cars sold for year 2006 in month #3: 1
Enter number of cars sold for year 2006 in month #4: 3
Enter number of cars sold for year 2006 in month #5: 4
Enter number of cars sold for year 2006 in month #6: 2
Total number of months:12
Total number of cars sold: 32
Average number of cars sold per month: 2.6666666666666665
Не стесняйтесь комментировать в случае любых сомнений / проблем.