Home > Software design >  I can't get the for loop to get the average of the integers, it keeps giving me 0s, but I need
I can't get the for loop to get the average of the integers, it keeps giving me 0s, but I need

Time:06-04

The code is supposed to get the average of the numbers after the first number, so for the first line [3 1 2 3] average is 2.0 because (1 2 3=6/3 = 2.0), but the code is just giving me 0s.

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);
       
    } 
}

CodePudding user response:

In your outer for-loop you initialize i with j and then go on to check, whether or not i < j. This condition will never be true and therefore your for-loop will never run a single time.

Although to me it doesn't look like you need the outer loop at all, since you never use i nor does the code make sense, if executed multiple times.

CodePudding user response:

Ok, you're making this very difficult. I recommend the following:

  • Use a scanner to read the values.
Scanner scanner = new Scanner(new File(..));

Then you can use scanner.nextInt() to read in the value as an int. If you need to see if more ints are available you can check scanner.hasNextInt()

  • There is no need to use an array as you can sum the values as you read them
  • The first value is the count so you can get the average (and use that as the loop count).
  • just make certain you sum the values in a double and not an int. Otherwise you will loose fractions. eg. 10/4 == 2 but 10./4 == 2.5

Check out Scanner for more information.

  •  Tags:  
  • java
  • Related