Как мне прочитать каждую строку? - PullRequest
0 голосов
/ 12 апреля 2020

Я пытаюсь добавить сумму каждой строки, но я могу вычислить только сумму первой строки? Как мне сделать так, чтобы программа шла и читала каждую строку для вычисления суммы?

Как только я это сделаю ... Я хочу добавить туда оператор if else. Я хочу, чтобы он спрашивал каждую строку, есть ли int выше 30000. Для каждого int, который превышает 30000, я хочу, чтобы к сумме прибавилось 1000.

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

Ответы [ 2 ]

0 голосов
/ 12 апреля 2020

Есть ряд вещей, которые можно было бы сделать по-другому здесь.

  • Прежде всего, рассмотрите возможность отказа от использования двух определенных c программ чтения файлов данных. В этом нет смысла, когда подойдет только одна программа для чтения файлов. Выбирайте и придерживайтесь его.
  • Какой бы файловый ридер вы ни решили использовать, обязательно закройте его, когда закончите.
  • Не открывайте файл данных с новым экземпляром ридера для каждой итерации , тогда как l oop. Вы создаете ловушку для этого файла каждый раз, когда делаете это, и он будет оставаться там до тех пор, пока каждый экземпляр читателя не будет закрыт или ваше приложение не завершится.

Объявление 12 указанных c int переменных для ежемесячного хранения значения могут лучше всего подходить с использованием массива. Вам также необходимо учитывать тот факт, что в данных могут быть (возможно, в какой-то момент) опечатка или ошибка, которые не приведут к действительному целочисленному значению. Это может привести к тому, что если вы не обработаете код, это может привести к неожиданным последствиям.

Ниже приведен код, демонстрирующий один из способов выполнения sh поставленной задачи. Он хорошо прокомментирован, поэтому вы можете видеть, что происходит:

// 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
0 голосов
/ 12 апреля 2020

Прежде всего, лучше объявить jan, feb et c. Переменные вне метода, потому что действительно похоже, что значения не обновляются. Но я бы порекомендовал вам что-то вроде этого:

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

   }


   }

Это должно быть лучше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...