Question

In: Computer Science

Assignment: Create data file consisting of integer, double or String values. Create unique Java application to...

Assignment:

Create data file consisting of integer, double or String values.

Create unique Java application to read all data from the file echoing the data to standard output. After all data has been read, display how many data were read. For example, if 10 integers were read, the application should display all 10 integers and at the end of the output, print "10 data values were read"

My issue is displaying how many integers were read and how many strings were read.

Here's my code:

/*

* File: ReadDateFile.java

* Author: Mia Robinson

* Date: 10/7/2020

* Purpose: This program will read data from a file

* and will echo the data to standard output

*/

package readdatafile;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

/**

*

* @author mrsar

*/

public class ReadDataFile {

  

  

  /**

   * @param args the command line arguments

   */

  public static void main(String[] args) {

    // TODO code application logic here

Scanner scannerIn = null;

FileInputStream in = null;

BufferedReader inputStream = null;

// int equivalent of the char

int fileChar;

String fileLine;

int intCount=0; // Initialize integer and word counter

String stringCount =0;

try {

in = new FileInputStream("Read.txt");

System.out.println("Fun with integers");

// Read one char at a time

while ((fileChar = in.read()) != -1) {

int length = String.valueOf(fileChar).length();  

  intCount += String.valueOf(fileChar).length();  

// convert int to char

System.out.print((char) fileChar);

}

// Print the number or string values read to the console   

   System.out.println("\n\n" + intCount + " data values were read!");   

// Separate the file output

System.out.println(" \n");

// Use of Scanner and BufferedReader

inputStream = new BufferedReader(new FileReader("ReadStrings.txt"));

System.out.println("We've reached the end:");

// Read one Line using BufferedReader

while ((fileLine = inputStream.readLine() ) != null) {

System.out.println(fileLine);

}

// Print the number or string values read to the console

      System.out.println("\n" + stringCount + " string values were read!");

} catch (IOException io) {

System.out.println("File IO exception" + io.getMessage());

} finally {

// Need another catch for closing

// the streams

try {

// Close the streams

if (in != null) {

in.close();

}

if (inputStream != null) {

inputStream.close();

}

} catch (IOException io) {

System.out.println("Issue closing the Files" +

io.getMessage());

}

  }

}

}

Solutions

Expert Solution

EDIT:

Hey, if you are using windows please specify you file path using "\\"

for example: "C:\\Downloads\\javaprograms\\filename"

----------------------------------------------------------------

Hey , by reading the question what I understood is :

1. There is a file which contains only numbers , assume Numbers.txt . We should read all the numbers and display the count.

2. There is another file which contains only String data , assume words.txt. We should read all the words ( separated by space ) and display the number of words.

3. And same with the double.

--------------------------------------------------------------------------------------------------------------------------------------------------------------

file-name:   ReadData.java
---------------------------------------------
import java.io.*;
import java.util.*;

/**
 *  We are using two different files here
 *  1. numbers.txt contains only numbers ( integers )
 *  2. words.txt contains only Strings 
 *  both files are in the same directory "/home/rahul/Pictures" ( here in my case )
 *  NOTE : You need to change the file-names and file-address as per your computer.
 *  if windows , your path address should be like "C:\\Downloads\\JavaFiles\\file-name" ( example )
 *  
 *  one thing to be remembered , when we read a file using buffered reader, br.readLine( )
 *  
 *  -> this always gives a String type as output, so it considers a 100 in file also as String "100"
 *  -> So, I used Integer.parseInt( ) for converting this String "100" to Integer type 100
 */
public class ReadData {

    // main method
    public static void main(String[] args) {
        // file-name and file-address
        String filename = "numbers.txt";
        String fileaddress = "/home/rahul/Pictures/";

        /*
        If you want to store the file data we can add it to the ArrayList, Here in the problem they asked to just display it.
         */
        // ArrayList<Integer> listOfIntegers = new ArrayList<>();
        // to count the number of integers.
        int count = 0;

        BufferedReader br;
        /**
         * try catch blocks for the purpose of exception handling
         * FileNotFoundException : This type of exception is raised, when there is no file in your specified location ( path )
         * IOException : This is raised if there is some I/O problem
         * NumberFormatException : This is raised when, the data which is read is not of desired type ( can't be stored in that primitive data type )
         * here we want to read an integer, so if we get a String value (example: "robinson" ) then NumberFormatException occurs.
         */
        try {
            br = new BufferedReader(new FileReader(fileaddress+filename));
            String line = br.readLine();
            while( line != null ) {
                int data = Integer.parseInt(line);
                System.out.println(data);
                count++;
                line = br.readLine();
            }
            br.close();
            System.out.println(count + " data values were read ");
        }
        catch(FileNotFoundException e) {
            System.out.println("No file with that name!!");
        }
        catch (IOException e) {
            System.out.println("No data!");
        }
        catch (NumberFormatException n){
            System.out.println("The value is not an Integer");
        }
        System.out.println("-----------------------------");
        /***********************************************************************/
        /**
         * Now we read data from words.txt, which contains only Strings ( separated by space " " )
         * We display those Strings and count
         */
         String filename2 = "words.txt";
         int stringCount = 0;
         try {
             br = new BufferedReader(new FileReader(fileaddress+filename2));
             String data = br.readLine();
             while( data != null ) {
                 String[] input = data.split(" ");
                 for(String s : input) {
                     System.out.println(s);
                     stringCount++;
                 }
                 data = br.readLine();
             }
             System.out.println(stringCount+ " data values were read");
         }
         catch(FileNotFoundException e) {
             System.out.println("No file with that name");
         }
         catch(IOException e) {
             System.out.println("IOException raised");
         }
    }  // END OF main( ) method
} // END OF ReadData class

--------------------------------------------------------------------------------------------------------------

OUTPUT:

THANK YOU !! If you have any doubt please ask in comment section , I will modify the answer ( add EDITS ) . If you like my effort please upvote.


Related Solutions

This is my java method that is suppose to take data from a file(String, String, Double,...
This is my java method that is suppose to take data from a file(String, String, Double, Int ) and load that data into an object array. This is what I have and when I try to display the contents of this array it prints a "@" then some numbers and letters. which is not the correct output. any help correcting my method would be much appreciated. public void loadInventory(String fileName) { String inFileName = fileName; String id = null; String...
In c++ Write a program that reads a string consisting of a positive integer or a...
In c++ Write a program that reads a string consisting of a positive integer or a positive decimal number and converts the number to the numeric format. If the string consists of a decimal number, the program must use a stack to convert the decimal number to the numeric format. Use the STL stack
Using Java create an application that will read a tab-delimited file that displays the MLB standings...
Using Java create an application that will read a tab-delimited file that displays the MLB standings Below: League AL East Tampa Bay 37 20 NY Yankees 32 24 Toronto 29 27 Baltimore 23 33 Boston 22 34 League AL Central Minnesota 35 22 Chi White Sox 34 23 Cleveland 33 24 Kansas City 23 33 Detroit 22 32 League AL West Oakland 34 21 Houston 28 28 LA Angels 26 31 Seattle 25 31 Texas 19 37 League NL East...
Create a C# application for SummerSchool that reads the file Participants. participant's data on the screen....
Create a C# application for SummerSchool that reads the file Participants. participant's data on the screen. Create a Participant class that contains field first name, last name, age, and course taken for the summer school and To fields of records in the file are separated with semicolon (). 3 marks) E.g. of a record in the file Participant.txt: 123,John,Smith35:Math using System; using static System. Console; using System. I0; class SummerSchool static void Main() /7Your code as answer
Java RECURSIVE methods: => intersection(String s1, String s2): takes two strings and returns the string consisting...
Java RECURSIVE methods: => intersection(String s1, String s2): takes two strings and returns the string consisting of all letters that appear in both s1 and s2. => union(String s1, String s2): takes two strings and returns the string consisting of all letters that appear in either s1 or s2. =>difference(String s1, String s2): takes two strings and returns the string consisting of all letters that appear only in s1.
Create a java Swing GUI application that presents the user with a “fortune”. Create a java...
Create a java Swing GUI application that presents the user with a “fortune”. Create a java Swing GUI application in a new Netbeans project called FortuneTeller. Your project will have a FortuneTellerFrame.java class (which inherits from JFrame) and a java main class: FortuneTellerViewer.java. Your application should have and use the following components: Top panel: A JLabel with text “Fortune Teller” (or something similar!) and an ImageIcon. Find an appropriate non-commercial Fortune Teller image for your ImageIcon. (The JLabel has a...
Using a minimum of 2 classes create a java program that writes data to a file...
Using a minimum of 2 classes create a java program that writes data to a file when stopped and reads data from a file when started. The data should be in a readable format and the program should work in a way that stopping and starting is irrelevant (e.g. all data doesn't have to save just the important elements.) Program should be unique and semi-complex in some way.
IN JAVA Searching and Sorting In An Integer List File IntegerList contains a Java class representing...
IN JAVA Searching and Sorting In An Integer List File IntegerList contains a Java class representing a list of integers. The following public methods are provided: ? IntegerList(int size)—creates a new list of size elements. Elements are initialized to 0. ? void randomize()—fills the list with random integers between 1 and 100, inclusive. ? void print()—prints the array elements and indices ? int search(int target)—looks for value target in the list using a linear (also called sequential) search algorithm. Returns...
Write a Java application with a JavaFXGUI that takes a String input by the user and...
Write a Java application with a JavaFXGUI that takes a String input by the user and shows whether the string contains all 26 letters of the (English version of the Latin) alphabet. For example, "Pack my box with five dozen liquor jugs" contains all 26 letters, but "The quick frown box jumps over the hazy log" does not contain a d. It does not matter whether one or more letters appear more than once. The GUI needs, at minimum, a...
Write a Java application with a JavaFXGUI that takes a String input by the user and...
Write a Java application with a JavaFXGUI that takes a String input by the user and shows whether the string contains all 26 letters of the (English version of the Latin) alphabet. For example, "Pack my box with five dozen liquor jugs" contains all 26 letters, but "The quick frown box jumps over the hazy log" does not contain a d. It does not matter whether one or more letters appear more than once. The GUI needs, at minimum, a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT