简体   繁体   中英

How to add string token numbers from a text file in Java

The text file(myfile.txt) has the numbers as follows:

6
19
20
23
34
45
47
51
54
56
61
70
72
76
90
93
94
96
105
111

I can read and print this text file in Java as a string token and my code is:

                      File fileName = new File("myfile.txt");         
                      Scanner inFile = new Scanner(fileName);        
                      while (inFile.hasNext())         
                      {         
                      token = inFile.next( ); 

                      System.out.println(token);

                      } 

                    inFile.close();

Now how can I get the sum of these numbers in java? I mean SUM(6+19+20+23+..........+111)

use an int variable sum , and use scanner.nextInt() to extract the number . and do the addition on every iteration.

                      File fileName = new File("myfile.txt");         
                      Scanner inFile = new Scanner(fileName);
                       int sum=0;        
                      while (inFile.hasNext())         
                      {         
                           sum+= inFile.nextInt( );     
                      } 
                      System.out.println(sum);

                    inFile.close();

You can convert your string to int using Integer.parseInt method. And then add it to a sum variable that you need to declare outside your while.

Scanner inFile = new Scanner(fileName);        
int sum = 0;
while (inFile.hasNext()) {         
    token = inFile.next( ); 

    System.out.println(token);
    sum += Integer.parseInt(token);

} 

Well, using inFile.nextInt() is a better option, if you are reading integer values. And use inFile.hasNextInt() in your while loop.

first read the integers using nextInt() of Scanner class into a List . Then add each of those numbers in the list using "enhanced" for loop

So I was able to figure out my problem and was successful, but I would still like anyone's input on if and how i could simplify this syntax by using a teranary operator.

import java.util.Scanner;
import java.io.*;
public class Midterm
{
    public static void main(String[]args) throws Exception
    {
     final String FILE = "integers.txt";
     final String RELATIVE_DIRECTORY_FILE = "integers.txt ";
    int positiveNumberCount = 0,
    negativeNumberCount = 0;
    String dataItem;
    double sum = 0;
    double sumForAverage = 0;
    double average = 0;

    File inputFile = new File(RELATIVE_DIRECTORY_FILE);
    if(!inputFile.exists())
    {
        System.out.printf("%n%s%s%s", "The file, ",   RELATIVE_DIRECTORY_FILE, " does not exist");
    }

    if(inputFile.exists())
    {
        System.out.printf("%s%s%s", "The file ", RELATIVE_DIRECTORY_FILE,       "was found");
        Scanner file = new Scanner(inputFile);
        //***if i need to use a delimiter *****
        //file.useDelimiter(",") where in between " "  is my type of delimiter
        while(file.hasNext())
        {



            dataItem = file.nextLine();

            double numericalDataItem = Double.parseDouble(dataItem);

            boolean isPositive = false;
            boolean isNegative = false;

            if(numericalDataItem > 0)
            {
                isPositive = true;
                positiveNumberCount++;
            }
            else if(numericalDataItem < 0)
            {
                isNegative = true;
                negativeNumberCount++;
            }

            sum += Double.parseDouble(dataItem);
            sumForAverage = positiveNumberCount + negativeNumberCount;
            average = sum/sumForAverage;

        } 
        System.out.printf("%n%s%d%n%s%d%n%s%.2f%n%s%.2f", "Positive Number Count: ", positiveNumberCount,
        "Negative Number Count: ", negativeNumberCount, "Sum Of Numbers: ", sum, "Average of Numbers: ", average);
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM