gpt4 book ai didi

java - 使用 while 循环从文件中读取

转载 作者:行者123 更新时间:2023-12-02 04:14:34 25 4
gpt4 key购买 nike

我的问题是:如何使用 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

最佳答案

只需进行最少的修改即可支持您请求的更改:

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

关于java - 使用 while 循环从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com