This program is supposed to read a text file which contains these integers -6 5 8 20 10 17 21 22 14 and then find the average.
I'm having an issue adding the value to itself inside the while loop and then using the final value of sum and using it outside the while loop.
public static void getAvg() throws IOException{
File file = new File
("C:\\Users\\Home Pc\\Desktop\\txtfiles\\q5.txt");
Scanner sc = new Scanner(file);
String nextval;
int i = 0, newvalInt,sum, avg, numofInts = 0;
while(sc.hasNext()) {
newvalInt = Integer.parseInt(sc.next());
sum =+ newvalInt; //<-- is this the proper way to keep adding a value to itself?
numofInts++;
}
avg = sum/numofInts; // <-- gives an error , can't access the sum variable inside the while loop
System.out.println("The average is: " + avg);
sc.close();
}
There are three main problems
sum =+ newvalInt;
should be sum += newvalInt;
sum
can not be used before be initialized, so int i = 0, newvalInt,sum = 0, avg, numofInts = 0;
sum
or numofInts
to be a double
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.