Question

In: Computer Science

Write a complete Java program that does the following: Open an input file named data.txt that...

Write a complete Java program that does the following:

  • Open an input file named data.txt that consists of a series of unknown number of integers. If data.txt does not exist, give an appropriate error message and terminate the program.
  • Define a constant MAX of value 100 and create an array of size MAX to hold items from the input file. Make sure your program will not generate ArrayIndexOutOfBounds exception.
  • Open an output file named result.txt and write the array elements in reverse order to result.txt. Make sure you write only the array elements that contain valid data items to the output file.

Solutions

Expert Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ReadWriteNumbers {
        public static void main(String[] args) {
                final int MAX = 100;
                //creating array with size 100
                int arr[] = new int[MAX];
                //opening the file to read data
                Scanner sc=null;
                try{
                        sc = new Scanner(new File("data.txt"));
                }
                catch (Exception e) {
                        System.out.println("data.txt does not exist");
                        return;
                }
                int index = 0;
                // looping through file and reading upto 100 integers
                while (sc.hasNextInt() && index < 100) {
                        arr[index] = sc.nextInt();
                        index++;
                }
                // opening file to write the data
                PrintWriter pw=null;
                try {
                        pw = new PrintWriter(new File("result.txt"));
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                // iterating array from backside to write results in reverse order
                for (int i = index - 1; i >= 0; i--)
                        pw.println(arr[i]);
                pw.close();
                System.out.println("Succes...");
        }
}

NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.

Please Like and Support me as it helps me a lot


Related Solutions

Write a program that creates an output file named rand_nums.txt. Open the file and write 100...
Write a program that creates an output file named rand_nums.txt. Open the file and write 100 random integers between -50 and +50 (inclusive) to the file. Be sure to handle any file IO exceptions. Remember to close the file. Write a program that opens rand_nums.txt for input. Create two output files pos.txt and neg.txt. Read through the input file, one line at a time, converting each line into an integer (no exception handling, yet). If the number is positive, write...
Write a Java program named, MultiTable, (MultiTable.java), with the following tasks: Prompt user to input the...
Write a Java program named, MultiTable, (MultiTable.java), with the following tasks: Prompt user to input the maximum number (as integer) Store a multiplication table for all combinations (with some specific eliminations) of value 0 through the maximum number (being entered) into a 2-D array Write a method named printTable to print out the MulitTable, with the following header, public static void printTable(int[][] multitable) In printTable(), when the value of the MultiTable is an odd number, print out Z Must use...
Write a Java program named, TicketSale, (TicketSale.java) with the following tasks: Prompt user to input the...
Write a Java program named, TicketSale, (TicketSale.java) with the following tasks: Prompt user to input the number of Adult tickets to purchase Prompt user to input the number of Children tickets to purchase Prompt user to input the number of Senior tickets to purchase Write a method named, ticketCost(), which will be invoked by main() with statement similar to: cost = ticketCost( adults, children, senior ); Ticket costs structure: $15.00 for each adult $10.00 for each child $5.00 for each...
Write a complete java program to get input of a person’s age and their years of...
Write a complete java program to get input of a person’s age and their years of current USA citizenship. Tell them if they are eligible to run for US House of Representatives, US Senate, or President. At first, have the program just run once and give the answer for the given inputs. Give the answer in a nice format and be clear which offices the person can run for. Write good and complete pseudo code. Next, put that program in...
Java Write a program that will only accept input from a file provided as the first...
Java Write a program that will only accept input from a file provided as the first command line argument. If no file is given or the file cannot be opened, simply print “Error opening file!” and stop executing. A valid input file should contain two lines. The first line is any valid string, and the second line should contain a single integer. The program should then print the single character from the string provided as the first line of input...
Write a C program that, given a file named Program_2.dat as input, determines and prints the...
Write a C program that, given a file named Program_2.dat as input, determines and prints the following information: The number of characters in the file. The number of uppercase letters in the file. The number of lowercase letters in the file. The number of words in the file. The number of lines in the file. Your program should assume that the input file, Program_2.dat, may contain any text whatsoever, and that text might be, or might not be, the excerpt...
Write a complete program in java that will do the following:
Write a complete program in java that will do the following:Sports:             Baseball, Basketball, Football, Hockey, Volleyball, WaterpoloPlayers:           9, 5, 11, 6, 6, 7Store the data in appropriate arraysProvide an output of sports and player numbers. See below:Baseball          9 players.Basketball       5 players.Football           11 players.Hockey            6 players.Volleyball        6 players.Waterpolo       7 players.Use Scanner to provide the number of friends you have for a team sport.Provide an output of suggested sports for your group of friends. If your...
3. Write a Java program that discover all anagrams of all wordslisted in the input file,...
3. Write a Java program that discover all anagrams of all wordslisted in the input file, “dict.txt”. An anagram of a work is a rearrangement of its letters into a new legal word. Your program should do the following: a. Read in the given “dict.txt” file and sort it in each word’s canonical form. The canonical form of a word contains the same letters as the original word, but in sorted order b. Instead of putting the “dict.txt” in the...
2. Write a Java program that reads a series of input lines from given file “name.txt”,...
2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file. Contents of names.text Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery,...
(C++) Write a program to read from a grade database (data.txt). The database (text file) has...
(C++) Write a program to read from a grade database (data.txt). The database (text file) has students names, and grades for 10 quizzes.Use the given function prototypes to write the functions. Have main call your functions. The arrays should be declared in main() and passed to the functions as parameters. This is an exercise in parallel arrays, int and char 2 dim arrays. Function prototypes: int readData(ifstream &iFile, int scores[][10], char names[][30]); This functions takes the file stream parameter inFile...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT