【问题标题】:How do I read each line?我如何阅读每一行?
【发布时间】: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 文件,但是当我开始尝试将整数相加时,它变得很不稳定。
  • 自上次审核以来您似乎进行了一些更改。

标签: java loops file int add


【解决方案1】:

首先,最好将janfeb 等变量声明出方法,因为看起来确实没有刷新值。 但我会向你推荐这样的东西:

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

   }


   }

这样应该会更好。

【讨论】:

  • 如有错误请指正,我会修改。
  • 哦,谢谢!我有点困惑这是怎么回事?你介意告诉我替换什么会更好吗?
  • 我在您的代码中插入了我的更正,可能会有奇怪的括号,但现在应该可以正常工作了。
【解决方案2】:

这里有很多事情可以做不同的事情。

  • 首先,考虑放弃使用两个特定数据文件的想法 读者。当只有一个文件阅读器可以做到时,这是没有意义的。 选择并坚持下去。
  • 无论您决定使用哪种文件阅读器,请确保在 完成。
  • 不要每次都使用新的阅读器实例打开数据文件 while 循环的迭代。您正在该文件上创建一个挂钩 每次你这样做,它会一直留在那里,直到每个读者 实例已关闭或您的应用程序结束。

声明 12 个特定的 int 变量来保存每月值可能最适合使用数组。您还需要考虑这样一个事实,即数据中可能(只是可能在某个时候)出现拼写错误或错误,不会产生有效的整数值。如果不加以处理,这可能会给代码的工作带来真正的古怪。

下面是一些代码,演示了您可以完成手头任务的一种方法。它的注释很好,因此您可以看到发生了什么:

// 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2022-08-17
    相关资源
    最近更新 更多