2010-05-17 121 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