2010-05-17 148 views
-2

對,所以爲什麼Java的想出這個錯誤:爪哇 - 最高,最低和平均

異常在線程「主要」 java.lang.Error的:未解決的問題,編譯: 類型不匹配:不能從雙轉換爲int

在rainfall.main(rainfall.java:38)

從這:

public class rainfall { 

/** 
    * @param args 
    */ 
public static void main(String[] args) 
{ 
int[] numgroup; 
numgroup = new int [12]; 
ConsoleReader console = new ConsoleReader(); 
int highest; 
int lowest; 
int index; 
int tempVal; 
int minMonth; 
    int minIndex; 
int maxMonth; 
int maxIndex; 


System.out.println("Welcome to Rainfall"); 
// Input (index now 0-based) 
for(index = 0; index < 12; index = index + 1) 
{  
    System.out.println("Please enter the rainfall for month " + index + 1); 
    tempVal = console.readInt(); 
    while (tempVal>100 || tempVal<0) 
    { 
     System.out.println("The rating must be within 0...100. Try again"); 
     tempVal = console.readInt(); 
    } 
    numgroup[index] = tempVal; 
}   

lowest = numgroup[0]; 
highest = numgroup[0]; 
int total = 0.0; 
// Loop over data (using 1 loop) 
for(index = 0; index < 12; index = index + 1) 
{  
    int curr = numgroup[index]; 
    if (curr < lowest) { 
     lowest = curr; 
     minIndex = index; 
    } 
    if (curr > highest) { 
     highest = curr; 
     maxIndex = index; 
    } 
     total += curr; 
} 
float avg = (float)total/numgroup.length; 

System.out.println("The average monthly rainfall was " + avg); 
// +1 to go from 0-based index to 1-based month 
System.out.println("The lowest monthly rainfall was month " + minIndex + 1); 
System.out.println("The highest monthly rainfall was month " + maxIndex + 1); 

System.out.println("Thank you for using Rainfall"); 

} 


private static ConsoleReader ConsoleReader() { 

    return null; 
} 

} 
+0

下一次請格式化你的代碼(使用編輯器上方的'101010'按鈕)。此外,如果您明確標記發生錯誤的代碼行,則會有所幫助... – 2010-05-17 10:34:24

回答

4

我猜的罪魁禍首就是這條線:

int total = 0.0; 

應該

int total = 0; 

代替。

+0

然後在此處引發錯誤: \t System.out.println(「最低月降雨量爲月」+ minIndex + 1); System.out.println(「最高月降雨量爲月」+ maxIndex + 1); – Emily 2010-05-17 10:33:58

+0

如果出現編譯錯誤,請嘗試使用括號,如'System.out.println(「最低月降雨量爲月」+(minIndex + 1));'。一般來說,請更具體地說明錯誤。 – 2010-05-17 10:36:00

+0

不,還是想出了這個錯誤:例外在線程「主要」 java.lang.Error的:未解決的編譯問題: \t局部變量minIndex可能沒有被初始化 \t局部變量maxIndex可能沒有被初始化,初始化 – Emily 2010-05-17 10:39:02

1

問題是這條線的位置:

int total = 0.0; 

需要改變總要float類型

+1

我認爲你的意思是'雙'。我不確定你爲什麼要使用'float',但如果你這樣做了,你需要將'0.0'改爲'0.0f'。 – Syntactic 2010-05-17 10:34:28

+0

只是爲了與示例中的其餘代碼保持一致 – 2010-05-17 10:40:15