[英]I can't get the for loop to get the average of the integers, it keeps giving me 0s, but I need the average of the numbers after the first number
代碼應該得到第一個數字之后的數字的平均值,所以對於第一行 [3 1 2 3] 平均值是 2.0 因為 (1 +2 +3=6/3 = 2.0),但代碼只是給我0。
public static void main(String[] args)throws IOException {
File num = new File("numbers.txt");
BufferedReader br = new BufferedReader(new FileReader(num));
String st;
int first, number ;
while((st = br.readLine())!= null){
int j= st.length()-1;
int average =0;
int i;
first = Integer.parseInt(st.substring(0, st.indexOf(" ")));
int sum = 0; // initialize sum
for( i = j;i< j; i++ ){
String str = st; //each line from the file
String [] segments = str.split(" ");
int [] values = Stream.of(segments)
.mapToInt(Integer::parseInt)
.toArray();
for (int c = 0; c < values.length; c++){
sum+=values[c];
}
sum = sum/first;
}
System.out.println("The average of the " + first + " integers"+ " "
+ st.substring(2) + " the average is "+ sum);
}
}
在您的外部 for 循環中,您使用j
初始化i
,然后繼續檢查是否i < j
。 這種情況永遠不會成立,因此您的 for 循環將永遠不會運行一次。
盡管在我看來,您根本不需要外部循環,因為您從不使用i
,如果多次執行,代碼也沒有意義。
好吧,你讓這變得非常困難。 我推薦以下內容:
Scanner scanner = new Scanner(new File(..));
然后您可以使用scanner.nextInt()
將值作為int 讀取。 如果您需要查看是否有更多整數可用,您可以檢查scanner.hasNextInt()
double
而不是 int。 否則你會丟失分數。 例如。 10/4 == 2
但10./4 == 2.5
查看掃描儀了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.