Reputation: 1
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
Upvotes: 0
Views: 1588
Reputation: 623
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);
Upvotes: 0
Reputation: 67
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);
Upvotes: 0
Reputation: 490
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.
Upvotes: 1
Reputation: 6659
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();
Upvotes: 1