Java - 阅读工资并获得总数

时间:2015-11-05 10:05:22

标签: java file loops math

所以基本上我从文本文件中读取一些工资,然后用“while”循环打印出来,然后我将它们与另一个“while”循环一起添加。

我的问题是,在运行代码时,我会将工资读入控制台,但我不会从第二个“while”循环中获得总薪水。

代码看起来像这样 -

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

4 个答案:

答案 0 :(得分:1)

#!/bin/bash

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
TBLLIST=""
COMMA=""
SQL="SELECT CONCAT(table_schema,'.',table_name) FROM information_schema.tables WHERE"
SQL="${SQL} table_schema NOT IN ('information_schema','mysql','performance_schema')"
for DBTB in `mysql ${MYSQL_CONN} -ANe"${SQL}"`
do
    echo OPTIMIZE TABLE "${DBTB};"
    SQL="OPTIMIZE TABLE ${DBTB};"
    mysql ${MYSQL_CONN} -ANe"${SQL}"
done

这不会返回true,因为已到达文件的末尾。 尝试在第一个while循环中总计你的总数:

while (scan.hasNextDouble()) {

您还可以在那里添加while (scan.hasNext()){ salaries = scan.nextDouble(); total += salaries; System.out.println(salaries); } 计数。

答案 1 :(得分:1)

你应该合并2个循环:

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

答案 2 :(得分:0)

不需要第二次循环。

    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);
        total += salaries;
    }

    double salary = total + items;
    System.out.println("Total salary = " + salary);

    scan.close();

在第一个循环中,扫描程序已完成其所有标记(元素)。

答案 3 :(得分:0)

当您退出第一个循环时,您已到达文件末尾。你应该再次初始化

scan = new Scanner(new File("salaries.txt")); 
第一次循环后

。您的代码将有效。