我正在尝试将每一行的总数相加,但是我只能计算第一行的总数?如何使程序运行并读取每一行以计算总数?
一旦执行此操作...我想在其中添加if else语句。我要问每一行是否有一个大于30,000的int。对于每个大于30,000的整数,我希望总数增加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
首先,最好从方法中声明jan
,feb
等变量,因为实际上看起来值没有被刷新。但我会建议您这样:
public class test(){
private int sum;
public static void main(String[] args)
{
readFromFile("sales.txt");
}
//You don't need this void to be static!
private 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);
for (int i = 0; i < 12; i++){
sum =+ a.nextInt();
}
System.out.println(sum);
sum = 0;
}
}
catch (Exception ex)
{
ex.printStackTrace();
} finally
{
//Close the LineNumberReader
try {
if (lineNumberReader != null){
lineNumberReader.close();
}
} catch (IOException ex){
ex.printStackTrace();
}
}
}
}
这应该更好。
这里有很多事情可以做不同的事情。
声明12个特定的int变量以保存每月值最适合使用Array。您还需要考虑以下事实:数据中可能存在错别字或错误,不会产生有效的整数值。如果不处理,这可能会给代码的工作带来麻烦。
下面是一些代码,展示了您可以完成手头任务的一种方法。评论很好,因此您可以查看发生了什么:
// Create a months header string for display purposes.
String header = String.format("%-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s",
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
// Create a header underline for display purposes.
String underline = String.join("", Collections.nCopies(header.length(), "="));
//Display a 'Start' underline for the Console display.
System.out.println(underline);
// Read the 'sales.txt' data file for monthly data of 6 stores.
// Trap the 'FileNotFoundException'.
try (Scanner reader = new Scanner(new File("sales.txt"))) {
int storeCounter = 0; // Keep track of the Store count.
long overallTotal = 0; // Maintain an Over-All total for all Stores
String line; // Used to hold current read in line data
// Iterate through the data file one line ata a time...
while (reader.hasNextLine()) {
line = reader.nextLine().trim(); // Trim leading/trailing whitespaces from read line.
if (line.equals("")) { continue; } // Skip blank lines (if any).
/* Split the line data into a String[] Array.
"\\s+" is used to split on one (or more)
whitespaces. */
String[] lineMonths = line.split("\\s+");
int yearTotal = 0; // Keep track of the line's yearly total.
storeCounter++; // Increment the Store Counter by 1.
int monthsOver30000 = 0; // Number of Months over 30000.
System.out.println("Store: " + storeCounter); // Display the Current Store Number in Console.
System.out.println(header); // Display the months header line in console.
// Display the current Store's monthly data in Console...
for (String month : lineMonths) {
// Display the current month.
System.out.printf("%-8s ", month);
// Add the current month value to the Yearly Total
// but first make sure it is in fact a valid integer
// value otherwise ignore it (don't add it to yearly).
if (month.matches("\\d+")) {
int monthValue = Integer.parseInt(month); // Convert the month value from string to integer
// Is the month value more than 30,000?
if (monthValue > 30000) {
// Yes, so add 1,000 to the Month Value
monthValue += 1000;
monthsOver30000++;
}
yearTotal += monthValue;
}
}
System.out.println(); // Add a newline to all the above printf's.
// If there were months that were over 30,000...
if (monthsOver30000 > 0) {
// Display information about it in Console.
System.out.println(); // Add a newline to separate this section.
System.out.println("There were " + monthsOver30000 + " months "
+ "for this Store where Monthly values were over 30000"
+ " therefore " + (monthsOver30000 * 1000) + " was added "
+ "to the");
System.out.println("Yearly Total.");
System.out.println(); // Add a newline to separate this section.
}
System.out.println("Yearly Total: --> " + yearTotal); // Display the yearly total in Console.
System.out.println(underline); // Display a underline so as to start a new data line.
// Add the current Year Total to the All Stores Over-All
// Total. Will be used for averaging later on.
overallTotal += yearTotal;
} // Continue iterating through data file until end of file is reached.
// Display the over-all total for all Stores Yearly totals in Console.
System.out.println("The over-all total for all " + storeCounter + " Stores: --> " + overallTotal);
// Display the yearly average for all stores contained within the data file.
System.out.println("The yearly average for all " + storeCounter + " Stores: --> " + overallTotal/storeCounter);
}
// Catch the 'FileNotFoundException' exception (if any).
catch (FileNotFoundException ex) {
// Display the Exception message if the exception was thrown.
System.err.println(ex.getMessage());
}
基于您在帖子中提供的数据,控制台的输出应类似于以下内容:
===========================================================================================================
Store: 1
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
There were 9 months for this Store where Monthly values were over 30000 therefore 9000 was added to the
Yearly Total.
Yearly Total: --> 444000
===========================================================================================================
Store: 2
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 591000
===========================================================================================================
Store: 3
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 21000
Yearly Total: --> 186000
===========================================================================================================
Store: 4
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 558000
===========================================================================================================
Store: 5
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 479000
===========================================================================================================
Store: 6
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 650000
===========================================================================================================
The over-all total for all 6 Stores: --> 2908000
The yearly average for all 6 Stores: --> 484666