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

  • What is the output of the following code? try { Scanner file = new Scanner(new File(“data.txt”));...

    What is the output of the following code? try { Scanner file = new Scanner(new File(“data.txt”)); int n = 0; while (file.hasNext()) { String s = file.nextLine(); if (s.equals(“A”))       n++; } System.out.println(“The value of n is “ +n); file.close(); } catch(IOException ioe) { ioe.printStackTrace(); }

  • 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...

  • Modify your program in Lab Assignment 4A to throw an exception if the file does not...

    Modify your program in Lab Assignment 4A to throw an exception if the file does not exist. An error message should result.   Use the same file name in your program as 4A, however, use the new input file in 4B assignment dropbox. My code: import java.io.*; import java.util.*; public class Lab4B { public static void main(String[] args) throws IOException { final String input_file = "Lab_4A.txt"; final String output_file = "Lab_4A.txt"; Scanner x = null; FileWriter y = null; try {...

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