簡體   English   中英

我無法讓 for 循環獲得整數的平均值,它一直給我 0,但我需要第一個數字之后的數字的平均值

[英]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 == 210./4 == 2.5

查看掃描儀了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM