Question

In: Computer Science

Could you please also give me a code that does not use the string split method...

Could you please also give me a code that does not use the string split method but instead gives an input and output file that you have to compile using "type output.txt" in java.

This is the code:

Record.java

public class Record {
private String stateCode, districCode, districtName;
private int totalPopulation, childPopulation, childPovertyPopulation;
private String miscStats;

public Record(String stateCode, String districCode, String districtName, int totalPopulation,
int childPopulation, int childPovertyPopulation, String miscStats) {
this.stateCode = stateCode;
this.districCode = districCode;
this.districtName = districtName;
this.totalPopulation = totalPopulation;
this.childPopulation = childPopulation;
this.childPovertyPopulation = childPovertyPopulation;
this.miscStats = miscStats;
}

public String getStateCode() {
return stateCode;
}

public String getDistricCode() {
return districCode;
}

public String getDistrictName() {
return districtName;
}

public int getTotalPopulation() {
return totalPopulation;
}

public int getChildPopulation() {
return childPopulation;
}

public int getChildPovertyPopulation() {
return childPovertyPopulation;
}

public String getMiscStats() {
return miscStats;
}
  
public double getChildPovertyPercent()
{
return(((double)getChildPovertyPopulation() / (double)getChildPopulation()) * 100);
}
}

ReadNWrite.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadNWrite {
  
public ReadNWrite(String inFileName, String outFileName)
{
ArrayList<Record> recs = readFromFile(inFileName);
writeToFile(outFileName, recs);
}
  
private ArrayList<Record> readFromFile(String fileName)
{
Scanner fileReader;
ArrayList<Record> recs = new ArrayList<>();
try
{
fileReader = new Scanner(new File(fileName));
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine().trim();
String[] data = line.split(",");
String stateCode = data[0];
String distCode = data[1];
String distName = data[2];
int population = Integer.parseInt(data[3]);
int childPopulation = Integer.parseInt(data[4]);
int childPovertyPopulation = Integer.parseInt(data[5]);
String miscStats = data[6];
recs.add(new Record(stateCode, distCode, distName, population, childPopulation, childPovertyPopulation
, miscStats));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println("Cannot locate file: " + fileName);
System.exit(0);
}
return recs;
}
  
private void writeToFile(String fileName, ArrayList<Record> recs)
{
FileWriter fw;
PrintWriter pw;
try {
fw = new FileWriter(new File(fileName), true);
pw = new PrintWriter(fw);
  
for(Record rec : recs)
{
pw.write(rec.getStateCode() + "," + rec.getTotalPopulation() + "," + rec.getChildPopulation()
+ "," + rec.getChildPovertyPopulation() + "," + rec.getChildPovertyPercent()
+ System.lineSeparator());
}
  
pw.flush();
fw.close();
pw.close();
} catch (IOException ex) {
System.out.println("Error in writing to file: " + fileName);
System.exit(0);
}
}
}

DisplayStatsMain.java

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

public class DisplayStatsMain {
  
private static final String INPUT_FILE = "PovertyData.txt";
private static final String OUTPUT_FILE = "PopulationSummary.txt";
  
public static void main(String[]args)
{
new ReadNWrite(INPUT_FILE, OUTPUT_FILE);
  
ArrayList<String> recs = readStatsFromFile(OUTPUT_FILE);
displayTabularStats(recs);
}
  
private static ArrayList<String> readStatsFromFile(String fileName)
{
Scanner fileReader;
ArrayList<String> recs = new ArrayList<>();
  
try
{
fileReader = new Scanner(new File(fileName));
while(fileReader.hasNextLine())
{
recs.add(fileReader.nextLine().trim());
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println("Cannot locate file: " + fileName);
System.exit(0);
}
return recs;
}
  
private static void displayTabularStats(ArrayList<String> recs)
{
System.out.printf("%5s %20s %20s %30s %20s\n-------------------------------------------------------------------"
+ "--------------------------------\n",
"State", "Population", "Child Population", "Child Poverty Population", "% Child Poverty");
for(String s : recs)
{
String[] data = s.split(",");
String state = data[0];
int totalPop = Integer.parseInt(data[1]);
int childPop = Integer.parseInt(data[2]);
int childPovertyPop = Integer.parseInt(data[3]);
double childPovertyPercent = Double.parseDouble(data[4]);
  
System.out.printf("%5s %20d %20d %30d %20.2f\n", state, totalPop, childPop, childPovertyPop, childPovertyPercent);
}
System.out.println();
}
}

Solutions

Expert Solution

Record.java

public class Record {

private String stateCode, districCode, districtName;
private int totalPopulation, childPopulation, childPovertyPopulation;
private String miscStats;

public Record(String stateCode, String districCode, String districtName, int totalPopulation,
int childPopulation, int childPovertyPopulation, String miscStats) {
this.stateCode = stateCode;
this.districCode = districCode;
this.districtName = districtName;
this.totalPopulation = totalPopulation;
this.childPopulation = childPopulation;
this.childPovertyPopulation = childPovertyPopulation;
this.miscStats = miscStats;
}

public String getStateCode() {
return stateCode;
}

public String getDistricCode() {
return districCode;
}

public String getDistrictName() {
return districtName;
}

public int getTotalPopulation() {
return totalPopulation;
}

public int getChildPopulation() {
return childPopulation;
}

public int getChildPovertyPopulation() {
return childPovertyPopulation;
}

public String getMiscStats() {
return miscStats;
}

public double getChildPovertyPercent() {
return (((double) getChildPovertyPopulation() / (double) getChildPopulation()) * 100);
}
}

ReadNWrite.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadNWrite {

public ReadNWrite(String inFileName, String outFileName) {
ArrayList<Record> recs = readFromFile(inFileName);
writeToFile(outFileName, recs);
}

private ArrayList<Record> readFromFile(String fileName) {
Scanner fileReader;
ArrayList<Record> recs = new ArrayList<>();
try {
fileReader = new Scanner(new File(fileName));
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine().trim();
String[] data = splitIntoTokens(line, ',');
String stateCode = data[0];
String distCode = data[1];
String distName = data[2];
int population = Integer.parseInt(data[3]);
int childPopulation = Integer.parseInt(data[4]);
int childPovertyPopulation = Integer.parseInt(data[5]);
String miscStats = data[6];
recs.add(new Record(stateCode, distCode, distName, population, childPopulation, childPovertyPopulation,
miscStats));
}
fileReader.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Cannot locate file: " + fileName);
System.exit(0);
}
return recs;
}

private void writeToFile(String fileName, ArrayList<Record> recs) {
FileWriter fw;
PrintWriter pw;
try {
fw = new FileWriter(new File(fileName));
pw = new PrintWriter(fw);

for (Record rec : recs) {
pw.write(rec.getStateCode() + "," + rec.getTotalPopulation() + "," + rec.getChildPopulation()
+ "," + rec.getChildPovertyPopulation() + "," + rec.getChildPovertyPercent()
+ System.lineSeparator());
}

pw.flush();
fw.close();
pw.close();
} catch (IOException ex) {
System.out.println("Error in writing to file: " + fileName);
System.exit(0);
}
}
  
// this method breaks a string into tokens based on a delimiter specified by the parameter 'delimiter'
private static String[] splitIntoTokens(String s, char delimiter)
{
int count = 0;
char[] ch = s.toCharArray();

for (int i = 0; i < ch.length; i++)
{
if (ch[i] == delimiter)
{
count++;
}
}
String dummy = "";
int index = 0;
String[] tokenBag = new String[count + 1];
for (int i = 0; i < ch.length; i++)
{
if (ch[i] == delimiter)
{
tokenBag[index++] = dummy;
dummy = "";
}
else
{
dummy = dummy + ch[i];
}
}
tokenBag[index] = dummy;
return tokenBag;
}
}

DisplayStatsMain.java (Main class)

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

public class DisplayStatsMain {

private static final String INPUT_FILE = "PovertyData.txt";
private static final String OUTPUT_FILE = "PopulationSummary.txt";

public static void main(String[] args) {
new ReadNWrite(INPUT_FILE, OUTPUT_FILE);

ArrayList<String> recs = readStatsFromFile(OUTPUT_FILE);
displayTabularStats(recs);
}

private static ArrayList<String> readStatsFromFile(String fileName) {
Scanner fileReader;
ArrayList<String> recs = new ArrayList<>();

try {
fileReader = new Scanner(new File(fileName));
while (fileReader.hasNextLine()) {
recs.add(fileReader.nextLine().trim());
}
fileReader.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Cannot locate file: " + fileName);
System.exit(0);
}
return recs;
}

private static void displayTabularStats(ArrayList<String> recs) {
System.out.printf("%5s %20s %20s %30s %20s\n-------------------------------------------------------------------"
+ "--------------------------------\n",
"State", "Population", "Child Population", "Child Poverty Population", "% Child Poverty");
for (String s : recs) {
String[] data = splitIntoTokens(s, ',');
String state = data[0];
int totalPop = Integer.parseInt(data[1]);
int childPop = Integer.parseInt(data[2]);
int childPovertyPop = Integer.parseInt(data[3]);
double childPovertyPercent = Double.parseDouble(data[4]);

System.out.printf("%5s %20d %20d %30d %20.2f\n", state, totalPop, childPop, childPovertyPop, childPovertyPercent);
}
System.out.println();
}
  
// this method breaks a string into tokens based on a delimiter specified by the parameter 'delimiter'
private static String[] splitIntoTokens(String s, char delimiter)
{
int count = 0;
char[] ch = s.toCharArray();

for (int i = 0; i < ch.length; i++)
{
if (ch[i] == delimiter)
{
count++;
}
}
String dummy = "";
int index = 0;
String[] tokenBag = new String[count + 1];
for (int i = 0; i < ch.length; i++)
{
if (ch[i] == delimiter)
{
tokenBag[index++] = dummy;
dummy = "";
}
else
{
dummy = dummy + ch[i];
}
}
tokenBag[index] = dummy;
return tokenBag;
}
}

********************************************************************* SCREENSHOT ******************************************************

Note: If you are not satisfied with the solution, feel free to explain your query in the comment section.


Related Solutions

Please give me an example of this java code. Vehicle - number: int - color: String...
Please give me an example of this java code. Vehicle - number: int - color: String - price: double - horsepower: double + Vehicle ( ) + Vehicle (int number) + Vehicle (int number, String color) + Vehicle (int number, String color, double price) + Vehicle (int number, String color, double price, double horsepower) +getnumber( ):int +setnumber(int number):void +getcolor( ):String +setcolor(String color):void +getprice( ):double +setprice(double price):void +gethorsePower( ):double +sethorsePower(double horsePower):void toString( ):String public String toString( ) { return "\n\n number...
Please write this code in C++, also if you could please bold the names of the...
Please write this code in C++, also if you could please bold the names of the input files and provide comments for each choice. For this part, the program gives the user 4 choices for encrypting (or decrypting) the first character of a file. Non-lowercase characters are simply echoed. The encryption is only performed on lowercase characters. If c is char variable, then islower(c) will return true if c contains an lowercase character, false otherwise To read a single character...
Please write code in c++ using iostream library. Also you can use any string library. Create...
Please write code in c++ using iostream library. Also you can use any string library. Create structure plane with the following: 1)plane's ID[int type] 2) location[char*] 3) departure time[char*] Your task is to find the plane with the smallest departure time for the selected city. Pointer, dynamic array and structures have to be used in this code. Input: NOTE: It's just an example of input, you should write code generally for any inputs. First line contains n(0 < n <...
client education for the disease pellagra. if you could please give me an outline for a...
client education for the disease pellagra. if you could please give me an outline for a paper
I need to fix this code, and could you please tell me what was the problem...
I need to fix this code, and could you please tell me what was the problem options 1 and 9 don't work #include <stdio.h> #include <time.h> #include <stdlib.h> // generate a random integer between lower and upper values int GenerateRandomInt(int lower, int upper){     int num =(rand()% (upper - lower+1))+lower;     return num; } // use random numbers to set the values of the matrix void InitializeMatrix(int row, int column, int dimension, int mat[][dimension]){     for(int i =0; i<row; i++){...
can you please give me short answers only 4 or 5 sentence and please could you...
can you please give me short answers only 4 or 5 sentence and please could you tpye the answers i do not want handwriting,,, You are creating a model for a manufacturing company with four major plants and ten warehouses. They want to reduce costs by determining the optimal number and location of the plants and warehouses. During the initial set of meetings, one of the team members is very concerned about modeling the “samples” that the firm sends out....
What Is Confidence Interval, and how can it be used? Could you please give me a...
What Is Confidence Interval, and how can it be used? Could you please give me a few examples and thanks so much.
Could you give me an answer as fast as you can? Please..! Thank You! Learning Objectives:...
Could you give me an answer as fast as you can? Please..! Thank You! Learning Objectives: Appendix E Analyze and report investments in held-to-maturity debt securities Analyze and report investments in available-for-sale securities Analyze and report investments in affiliated companies using the equity method Analyze and report controlling interests in other corporations using consolidated financial statements Report investing activities on the statement of cash flows Explain the impact of the time value of money on certain types of investments EXAMPLE...
Could you give me an answer as fast as you can. Please..! Thank You! Learning Objectives:...
Could you give me an answer as fast as you can. Please..! Thank You! Learning Objectives: CHAPTER 7 Measure and account for the cost of plant assets Distinguish a capital expenditure from an immediate expense Measure and record depreciation on plant assets Analyze the effect of a plant asset disposal Apply GAAP for natural resources and intangible assets Explain the effect of an asset impairment on the financial statements Analyze rate of return on assets Analyze the cash flow impact...
Also please add comments on the code and complete in C and also please use your...
Also please add comments on the code and complete in C and also please use your last name as key. The primary objective of this project is to increase your understanding of the fundamental implementation of Vigenere Cipher based program to encrypt any given message based on the Vignere algorithm. Your last name must be used as the cipher key. You also have to skip the space between the words, while replicating the key to cover the entire message. Test...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT