简体   繁体   中英

Using while-loop to read from a file

My question is: How do I use a while-loop to read inputs from a file ??

I wrote this code and I wonder how can I write it again in another way using a While-loop.


Scanner infile = new Scanner(new FileReader("while_loop_infile.in"));

    int sum;
    int average;
    int N1, N2, N3,N4,N5, N6, N7, N8, N9, N10;

    N1= infile.nextInt();
    N2= infile.nextInt();
    N3= infile.nextInt();
    N4= infile.nextInt();
    N5= infile.nextInt();
    N6= infile.nextInt();
    N7= infile.nextInt();
    N8= infile.nextInt();
    N9= infile.nextInt();
    N10= infile.nextInt();

    sum = N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 + N10;
    average = sum / 10;

    System.out.println("The sum is " + sum);
    System.out.println("The average is " + average);

    infile.close();

-------------------- This is the input file ------------------------------

10
20
30
40
50
60
70
80
90
100

With minimal modifications to just support the change you requested:

Scanner infile = new Scanner(new FileReader("while_loop_infile.in"));

int sum;
int average;
int N[10];
int i = 0;

while (i < 10) {
    N[i] = infile.nextInt();
    sum += N[i];
    i++;
}   

average = sum / 10; 

System.out.println("The sum is " + sum);
System.out.println("The average is " + average);

infile.close();

The Scanner class has several methods for this. Most basic of which is hasNext() .

This method returns true if there is a token to be read.

while(myScanner.hasNext()){
    // Read next input.
}

EDIT: Here is the documentation .

Scanner in = new Scanner(new BufferedReader(new FileReader());
double sum = 0.0;
int count = 0;
while (in.hasNext()) {
    sum += in.nextInt();
    count++;
}
System.out.println("The sum is " + sum);
System.out.println("The average is " + sum/count);

Duplicate question, read numbers from a file

Scanner in = new Scanner(new BufferedReader(new FileReader());  
double sum = 0.0;
int count = 0;
while(in.hasNext()) {
  if(in.hasNextInt()) {
    sum += in.nextInt();
  }
}
System.out.println("Average is " + sum/count);

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