Question

How to write a Java file out that that reads from numbers.txt with these numbers 2...

How to write a Java file out that that reads from numbers.txt with these numbers

2 6 7 9
5 4 3
8 0 1 6 8
2 3

and write to a file called totalSum.txt that looks like:

2+6+7+9=24 and so on using this code

import java.io.*;
import java.util.Scanner;

public class FileScanner
{

   public static void main(String[] args)
   {
       /* For Homework! Tokens*/
       Scanner file = null;
       PrintWriter fout= null;
       try {
           file = new Scanner(new File("numbers.txt"));
           fout = new PrintWriter("TotalSum.txt");
           while(file.hasNext())
           {
              
               @SuppressWarnings("resource")
               Scanner line = new Scanner(file.nextLine());
               int totalSum = 0;
               while(line.hasNext())
               {
                   int number = line.nextInt();
                   totalSum+=number;
                   fout.println( totalSum );
              
               }
               fout.println( " = "+totalSum);
           }  
       }
       catch (FileNotFoundException e)
       {
          
           System.out.println("NOT FOUND");
       }
       finally
       {
           if(fout!=null)fout.close();
       }
      
       if(file!=null)file.close();
      
   }
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.*;
import java.util.Scanner;

public class FileScanner {

    public static void main(String[] args) {
        /* For Homework! Tokens*/
        Scanner file = null;
        PrintWriter fout = null;
        try {
            file = new Scanner(new File("numbers.txt"));
            fout = new PrintWriter("TotalSum.txt");
            while (file.hasNext()) {
                @SuppressWarnings("resource")
                Scanner line = new Scanner(file.nextLine());
                int totalSum = 0;
                while (line.hasNext()) {
                    int number = line.nextInt();
                    totalSum += number;
                    fout.print(number);
                    if (line.hasNext()) {
                        fout.print("+");
                    }
                }
                fout.println("=" + totalSum);
            }
        } catch (FileNotFoundException e) {
            System.out.println("NOT FOUND");
        } finally {
            if (fout != null) fout.close();
        }

        if (file != null) file.close();
    }
}
Add a comment
Know the answer?
Add Answer to:
How to write a Java file out that that reads from numbers.txt with these numbers 2...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private...

    import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private static final String OUTPUT_FILE = "crimes.txt"; public static void main(String[] args) { int totalCrimes = 0; // read all the rows from the csv file and add the total count in the totalCrimes variable try { Scanner fileScanner = new Scanner(new File(INPUT_FILE)); String line = fileScanner.nextLine(); // skip first line while (fileScanner.hasNext()) { String[] tokens = fileScanner.nextLine().split(","); if (tokens.length == 4) { totalCrimes +=...

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • I have a program that reads a file and then creates objects from the contents of...

    I have a program that reads a file and then creates objects from the contents of the file. How can I create a linked list of objects and use it with the package class instead of creating and using an array of objects? I am not allowed to use any arrays of objects or any java.util. lists in this program. Runner class: import java.util.Scanner; import java.io.*; class Runner { public static Package[] readFile() { try { File f = new...

  • 1. Import file ReadingData.zip into NetBeans. Also, please download the input.txt file and store it into...

    1. Import file ReadingData.zip into NetBeans. Also, please download the input.txt file and store it into an appropriate folder in your drive. a) Go through the codes then run the file and write the output with screenshot (please make sure that you change the location of the file) (20 points) b) Write additional Java code that will show the average of all numbers in input.txt file (10 points) import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.*; 1- * @author mdkabir...

  • Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all...

    Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all the even numbers over 50. Print the result to the console using System.out.println(); The file will only have numbers. Code: import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; /** * * @author David */ public class ReadingFiles {     /**      * @param args the command line arguments      */     public static void main(String[] args) throws FileNotFoundException {         // TODO code application logic here...

  • JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out...

    JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out the name of the student with the lowestgpa. In the attached zip file, you will find two files HighestGPA.java and students.dat. Students.dat file contains names of students and their gpa. Check if the code runs correctly in BlueJ or any other IDE by running the code. Modify the data to include few more students and their gpa. import java.util.*; // for the Scanner class...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • Write a Java method that will take an array of integers of size n and shift...

    Write a Java method that will take an array of integers of size n and shift right by m places, where n > m. You should read your inputs from a file and write your outputs to another file. Create at least 3 test cases and report their output. I've created a program to read and write to separate files but i don't know how to store the numbers from the input file into an array and then store the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT