使用while循环从文件中读取

时间:2015-11-01 04:10:45

标签: java loops netbeans while-loop filereader

我的问题是:如何使用while循环读取文件中的输入?

我编写了这段代码,我想知道如何使用While循环以另一种方式再次编写代码。

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

--------------------这是输入文件---------------------- --------

10
20
30
40
50
60
70
80
90
100

4 个答案:

答案 0 :(得分:1)

只需进行少量修改即可支持您所要求的更改:

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

答案 1 :(得分:1)

Scanner类有几种方法。其中最基本的是hasNext()

如果有要读取的令牌,此方法将返回true

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

编辑:Here is the documentation

答案 2 :(得分:0)

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

答案 3 :(得分:0)

重复问题,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);