基本上,我从文本文件中读取一些薪水,然后用"while“循环将它们打印出来,然后将它们与另一个"while”循环相加。
我的问题是,在运行代码时,我会将工资读出到控制台中,但我不知道第二个“when”循环中的总薪资。
密码是这样的-
package Week15;
import java.util.*;
import java.io.*;
public class h {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(new File("salaries.txt"));
double items = 0;
double total = 0;
double salaries;
while (scan.hasNext()){
salaries = scan.nextDouble();
System.out.println(salaries);
}
while (scan.hasNextDouble()) {
// add the next salary to the total
total += scan.nextDouble();
// increase the number of encountered salaries by 1
items++;
}
double salary = total+items;
System.out.println("Total salary = " + salary);
scan.close();
}
}控制台看起来是这样的-
14390.75
12345.99
27512.08下面是我使用的"salaries.txt“文件的样子-
14390.75
12345.99
27512.08发布于 2015-11-05 10:08:52
当您退出第一个循环时,您已经到达了文件的末尾。您应该再次初始化
scan = new Scanner(new File("salaries.txt")); 第一圈之后。你的代码会起作用的。
发布于 2015-11-05 10:08:01
while (scan.hasNextDouble()) {这不返回true,因为已到达文件的末尾。试着在第一个while循环中总结您的总数:
while (scan.hasNext()){
salaries = scan.nextDouble();
total += salaries;
System.out.println(salaries);
} 您还可以在那里添加items计数。
发布于 2015-11-05 10:08:15
您应该合并这两个循环:
while (scan.hasNext()) {
salaries = scan.nextDouble();
System.out.println(salaries);
// add the next salary to the total
total += salaries;
// increase the number of encountered salaries by 1
items++;
}否则,第一个循环将完成对文件的扫描,当scan.hasNextDouble()返回false时,您永远不会进入第二个循环。
https://stackoverflow.com/questions/33541674
复制相似问题