我想執行一個名爲AverageRainfall的程序。大部分的輸入效果很好(開始時我的while語句很好),但變量monthRain下有多個月,並且monthRain的while語句在各個月份不起作用,只有初始輸入命令正在服務沒有目的。執行程序時,額外的輸入命令會導致邏輯錯誤java
ETA:過帳整個代碼進行測試
import java.util.Scanner; //for Scanner class
public class AverageRainfall
{
public static void main(String[] args)
{
final int NUM_MONTHS = 12; //Months per year
int years; //Number of years
double monthRain; //Rain for a month
double totalRain = 0; //Rainfall accumulator
double average; //Average rainfall
Scanner keyboard = new Scanner(System.in);
{
System.out.print("Enter the number of years: ");
years = keyboard.nextInt();
while (years < 1)
{
System.out.print("Invalid. Enter 1 or greater: ");
years = keyboard.nextInt();
}
}
{
System.out.println("Enter the rainfall, in inches, for each month. ");
monthRain = keyboard.nextDouble();
for(int y = 1; y <= years; y++){
for(int m = 1; m <= NUM_MONTHS; m++){
System.out.print("Year" + y + "month" + m + ": ");
monthRain = keyboard.nextDouble();
}
}
while (monthRain < 0)
{
System.out.print("Invalid. Enter 0 or greater: ");
monthRain = keyboard.nextDouble();
}
}
{
totalRain += monthRain;
average = totalRain/(years * NUM_MONTHS);
System.out.println("\nNumber of months: " + (years * NUM_MONTHS));
System.out.println("Total rainfall: " + totalRain + " inches");
System.out.println("Average monthly rainfall: " + average + " inches");
}
}
}
這是整個代碼。
可以發佈整個代碼,以便我可以測試它嗎? – 2015-03-31 05:03:55
是發佈完整的代碼。很難猜測。但我認爲最近發生的事情是totalRain + = monthRain;不在循環中,這就是所有月份都沒有考慮到的原因 – Yantraguru 2015-03-31 05:19:45
@Kognizant我會如何將它放在循環中? – LizzySmit 2015-03-31 05:42:16