【发布时间】:2020-04-11 22:04:30
【问题描述】:
我正在尝试添加每一行的总数,但我只能计算第一行的总数?如何使程序运行并读取每一行以计算总数?
一旦我这样做了……我想在里面放一个 if else 语句。我希望它询问每一行是否有一个大于 30,000 的 int。对于每个大于 30,000 的 int,我希望总数加 1,000。
package finalProg;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Scanner;
public class test
{
public static void main(String[] args)
{
readFromFile("sales.txt");
}
private static void readFromFile(String filename)
{
LineNumberReader lineNumberReader = null;
try
{
//Construct the LineNumberReader object
lineNumberReader = new LineNumberReader(new FileReader(filename));
//Setting initial line number
lineNumberReader.setLineNumber(0);
//Read all lines now; Every read increase the line number by 1
String line = null;
while ((line = lineNumberReader.readLine()) != null)
{
System.out.println("Store " + lineNumberReader.getLineNumber() + ": " + line);
File inputFile = new File("sales.txt");
Scanner a = new Scanner(inputFile);
int jan = a.nextInt();
int feb = a.nextInt();
int mar = a.nextInt();
int apr = a.nextInt();
int may = a.nextInt();
int jun = a.nextInt();
int jul = a.nextInt();
int aug = a.nextInt();
int sept = a.nextInt();
int oct = a.nextInt();
int nov = a.nextInt();
int dec = a.nextInt();
System.out.println(jan + feb + mar + apr + may + jun + jul + aug + sept + oct + nov + dec + "\n");
}
}
catch (Exception ex)
{
ex.printStackTrace();
} finally
{
//Close the LineNumberReader
try {
if (lineNumberReader != null){
lineNumberReader.close();
}
} catch (IOException ex){
ex.printStackTrace();
}
}
}
}
20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 21000
44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
到目前为止,输出如下所示:
Store 1: 20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
435000
Store 2: 35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
435000
Store 3: 20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 210000
435000
Store 4: 44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
435000
Store 5: 33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
435000
Store 6: 50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
435000
【问题讨论】:
-
看起来输入和输出文件在您的代码中是多余的。此外,您不要在
main()void 中使用BONUS()。 -
您能否详细说明究竟是什么不起作用:它会引发错误/异常还是无法正常工作?
-
@coder-coder 如何将 BONUS() 添加到我的主要方法中?
-
我似乎无法输出任何东西...之前我正在打印我的 sales.txt 文件,但是当我开始尝试将整数相加时,它变得很不稳定。
-
自上次审核以来您似乎进行了一些更改。