我在这项任务中遇到了很多错误。我尽可能多地完成了它并且似乎按顺序完成了一切,但JGrasp告诉我有49个错误。我在第30,31,33,36,37,40,41,42,43,47,48,54,55,56和57行遇到错误。根据我的教科书,我做的一切都是正确的。我该如何解决这个问题?
我在每一行给我带来麻烦之后添加了“here”评论。
完整计划:
import java.util.Scanner;
public class AverageRainfall {
public static void main(String[] args) {
double monthRain = 0; // Rain for a month
double totalRain = 0; // Rainfall accumulator
double average = 0; // Average rainfall
// Keyboard input.
Scanner keyboard = new Scanner(System.in);
// Number of years.
System.out.print("Enter the number of years: ");
int years = 0; // Number of years
years = keyboard.nextInt();
// Checks input.
while (years < 1) {
System.out.print("Invalid. Enter 1 or greater: ");
input anotheryears = keyboard.nextInt();
}
}
final int NUM_MONTHS = 12; // Months per year
System.out.println("Enter the rainfall, in inches, for each month."); //here
for (int y = 1; y <= years; y++); //here
{
for (int m = 1; m <= NUM_MONTHS; m++); //here
{
// Gets rainfall for each month.
System.out.print("Year " + y + " month " + m + ": "); //here
monthRain = keyboard.nextDouble(); //here
// Checks input.
while (monthRain < 0) //here
{ //here
System.out.print("Invalid. Enter 0 or greater: "); //here
monthRain = keyboard.nextDouble(); //here
}
// Accumulates rainfall.
totalRain += monthRain; //here
} //here
}
// Calculates average rainfall.
average = totalRain / (years * NUM_MONTHS);
// Displays statistics.
System.out.println("\nNumber of months: " + (years * NUM_MONTHS)); //here
System.out.println("Total rainfall: " + totalRain + " inches"); //here
System.out.println("Average monthly rainfall: " + average + " inches"); //here
}
答案 0 :(得分:2)
缩进代码。主要问题在于:
public static void main(String[] args) {
double monthRain = 0;
//more code...
while (years < 1) {
System.out.print("Invalid. Enter 1 or greater: ");
input anotheryears = keyboard.nextInt();
}
} //<--- here
//you're closing the main method
//and then you have more code outside of it
final int NUM_MONTHS = 12; // Months per year
System.out.println("Enter the rainfall, in inches, for each month."); //here
for (int y = 1; y <= years; y++); //here
//rest of code
除此之外,请在for
语句后删除分号:
for (int y = 1; y <= years; y++); //<-- remove this
应该是这样的:
for (int y = 1; y <= years; y++) {
//rest of code...
}
答案 1 :(得分:1)
你已经关闭了你的主要块,所以年份变量超出了奇怪的没有方法块的语句的范围。
我认为你在某个地方有一个额外的大括号,或者缺少一个大括号。