简体   繁体   中英

Adding a value to itself inside a while loop also, taking the final value and using it outside the loop

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM