2015-11-01 76 views
0

我的問題是:如何使用while循環從文件中讀取輸入?使用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 
+0

重複的問題,[從文件中讀取下一個INT](http://stackoverflow.com/questions/23676834/infinite-loop-on-scanner-hasnext - 從文件中讀取) –

+0

@ gatech-kid這甚至沒有與此相似。 – Alexander

回答

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

Scanner類有這幾種方法。其中最基本的是hasNext()

如果存在要讀取的令牌,則此方法返回true。編號:Here is the documentation

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); 
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); 
相關問題