Creating Multiple Arrays From a Text File in JAVA - java

I'm in a low level program design class and am struggling with creating arrays from data given in a text file. The file name is students.txt and it is formatted in this manner:
1234
Joseph
3
4.0 (except it is single spaced)
Where the first number (an integer) is the Student ID, followed by the student name, followed by credit hours, and finished with GPA. This is an example of course and the file contains many records.
In the end I am going to create a record that is organized in sequential order by one of the fields above. What I need help with is creating multiple arrays for each field. I'm thinking it would be very helpful if I could have a student_ID array, name array, credit_hour array, and gpa array.
Here is my best shot and attempt:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package filetoarray;
import java.util.*;
import java.io.*;
/**
*
* #author whitn
*/
public class FileToArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args)throws IOException {
//Here I am establishing my arrays
int[]student_ID;
student_ID = new int[100];
String[]name;
name = new String[100];
int[]credit_hour;
credit_hour = new int[100];
double[]gpa;
gpa = new double[100];
// I am not too sure what FileReader and BufferedReader do but I think
// I am creating a way for the program to read from the file students.txt
FileReader fr = new FileReader ("C:\\Users\\whitn\\Desktop\\students.txt");
BufferedReader snames = new BufferedReader(fr);
//Here I am initializng my variables
String name1 = " "; //called name1 to not confuse it with array 'name'
String next = " ";
int s_ID = 0;
int c_hour = 0;
double gpa1 = 0.0;
//Now I don't really know how to proceed. Do use something like
// student_ID[x] = Integer.parseInt(next)
// name[x] = snames.nextLn();
// credit_hour[x] = snames.nextInt();
// gpa[x] = snames.nextDouble();
//Do I even need the variable initialized above?
}
}
I'm pretty sure if I can figure out how to create an array from the fields provided in the file I can finish the problem. Any help would be greatly appreciated. I am in my first programming class and don't know much, therefore, if I've left out valuable information let me know!
Thank you

You can use readline method of bufferreader to read line by line and that's how you pick one record in the form of string.
Now if are separated by space or comma , you can use string method split which will return you an array of string now by index you can assign values to all your variable by that array of string or you can directly use that array of string

Make a class for reading file content like
import java.io.*;
public class FileReader {
private String fileName, fileContent = null, line;
public FileReader(String f) {
fileName = f;
reader();
}
private void reader() {
try {
fileContent = "";
// FileReader reads text files in the default encoding
Reader fileReader = new java.io.FileReader(fileName);
// Wrapping FileReader in BufferedReader
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
fileContent += line;
fileContent += '\n';
}
// Closing the file
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
}
/**
* Get content of file
*
* #return String
*/
public String getFileContent() {
return fileContent;
}
}
Create a class for Student
public class Student {
public String name;
public int id, creditHour;
public double gpa;
// add constructor and setter/getter methods
}
Create a class for starting project with main method. get file content from FileReader class. Define an array of students. Loop over its content and fill your array.

Related

How do I add a line between words/numbers from a String Array in Java?

Confusing title, but all I want to know is how do I break up a long line of words, or in this case numbers.
I am jotting down zip codes of a town/city that a user types in. Some towns/cities have a lot of zip codes and the output is quite long.
I want to break up these lines at every 100 characters so they're easier to read.
I would like output to look like this:
You asked me to search for place: Chicago, Il
Chicago, Il has zip codes: [60601, 60602, 60603, 60604, 60605, 60606,
60607, 60608, 60609, 60610, 60611, 60612, 60613, 60614, 60615, 60616,
60617, 60618, 60619, 60620, 60621, 60622, 60623, 60624, 60625, 60626,
60628, 60629, 60630, 60631, 60632, 60633, 60634, 60636, 60637, 60638,
60639, 60640, 60641, 60643, 60644, 60645, 60646, 60647, 60649, 60651,
60652, 60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60663,
60664, 60665, 60667, 60668, 60669, 60670, 60671, 60672, 60673, 60674,
60675, 60677, 60678, 60679, 60680, 60681, 60683, 60684, 60685, 60687,
60690, 60691, 60693, 60694, 60697, 60699, 60701]
^^^ My current output is that, but all in one line. ^^^
I want to know how I can fix it so it looks like that. Here is my current code at the moment.
import java.util.ArrayList;
import java.io.*;
import java.util.*;
/**
* In this class, I will obtain two private variables that are a type
String and ArrayList.
* The String will be the location that the user types in and the zip
code will be the zip codes
* that exist within that town/city.
*/
public class Place
{
private ArrayList<String> zipCodes;
private String location;
/**
* In this method, we find the file in which we will retrieve this
data. We put it in a Scanner and
* put each line in an ArrayList that is ZipCodes.
* #throws FileNotFoundException if the file doesn't exist.
*/
public Place() throws FileNotFoundException
{
File zipsFile = new File("/Users/adanvivero/IdeaProjects/assignment
6/zips.txt");
zipCodes = new ArrayList<String>();
Scanner coordinates = new Scanner(zipsFile);
while(coordinates.hasNextLine())
{
String lineScan = coordinates.nextLine();
zipCodes.add(lineScan);
}
}
/**
* In this method, we print out the zip code of the town/city in which
the user typed in.
* #throws FileNotFoundException We use this since we used a file in
the String method, setZipCode
* down below.
*/
public void addPlace() throws FileNotFoundException
{
String theSummary = location + " has zip codes: " + setZipCodes();
if(theSummary.length() > 100)
{
System.out.println();
System.out.print(theSummary);
}
}
/**
* In this method, we retrieve the zip code of the city/town. I have
two ArrayList since I don't need
* to get the coordinates of the file, but rather only the name of the
town and the zip code of it. Therefore,
* I add the zip codes into one of the ArrayList, which in this
instance happen to be our private one, and
* the name of the location in another Arraylist.
* #return We return a String that will be the zipCodes which is in an
Array, but converted as a String.
* #throws FileNotFoundException We retrieve the file in which these
will come out in. If the file doesn't exist,
* we throw a FileNotFoundException.
*/
public String setZipCodes() throws FileNotFoundException
{
File zipsFile = new File("/Users/adanvivero/IdeaProjects/assignment
6/zips.txt");
//ArrayList<String> zips = new ArrayList<String>();
zipCodes = new ArrayList<String>();
ArrayList<String> codes = new ArrayList<String>();
Scanner console = new Scanner(zipsFile);
while(console.hasNextLine())
{
String z = console.nextLine();
String [] zip = z.split("\t");
String [] code = z.split("\t");
if(location.equalsIgnoreCase(code[3]))
{
zipCodes.add(zip[0]);
codes.add(code[3]);
}
}
String theSummary = zipCodes.toString();
for(int i = 0; i <= theSummary.length()-1; i++)
{
while(theSummary.charAt(i) == 100)
{
System.out.println();
}
}
return zipCodes.toString();
}
/**
* In this String method, we as the user to type in a place and we
return the place the user typed in so other
* methods can use it.
* #return it returns the String of the location the user types in.
*/
public String getLocation()
{
Scanner wuddup = new Scanner(System.in);
System.out.print("You asked me to search for place: ");
location = wuddup.nextLine();
return location;
}
}
So I believe to solve my problem is under the setZipCode() method or on my addPlace() method.
In addPlace() do this:
String theSummary = location + " has zip codes: " + setZipCodes();
String theNewSummary = "";
for(int i = 0; i < theSummary.length()-1; i = i+100){
if(i+99 < theSummary.length()-1)
theNewSummary += theSummary.substring(i, i+99)+"\r\n";
else
theNewSummary += theSummary.substring(i, theSummary.length()-1);
}
System.out.print(theNewSummary );
In order to display 10 zipcodes per line:
String theSummary = location + " has zip codes: \r\n";
String[] zipCodes = setZipCodes().split(" ");
for(int i = 0; i < zipCodes.length; i++){
theSummary += " "+zipCodes[i];
if(i%10 == 0 && i !=0)
theSummary +="\r\n"
}
System.out.print(theSummary );
From addPlace() you can call this method to format the output.
The advantages of this method are that it can:-
Split the string in any length
Doesn't break the line in the middle of the zip code.
Working code :-
/**
* Format a String to specific line length.
* #param summary : Input string
* #param maxLineLength Max line length.
* #param delim String delimeter to be used for breaking the string like space or comma
* #return the formated sting
*/
public static String formatSummary(String summary, int maxLineLength, String delim) {
//convert long string to array of word by delim and discard empty string.
List<String> summarySplitByDelim = Arrays.stream(summary.split(delim)).filter(a->a.length() > 0)
.collect(Collectors.toList());
String newLine = System.getProperty("line.separator");
StringBuilder formattedSummary = new StringBuilder();
StringBuilder currentLine = new StringBuilder();
for (String currentWord : summarySplitByDelim) {
// Keep on adding word by word to currentline
currentLine.append(currentWord.trim()).append(delim);
//if current line execeed our line length, dump everything to formatedSummary and reset currentline
if(currentLine.length() > maxLineLength){
formattedSummary.append(currentLine).append(newLine);
currentLine = new StringBuilder();
}
}
//Add the last line if not added because the loop exited.
if(currentLine.length() > 0){
formattedSummary.append(currentLine).append(newLine);
}
return formattedSummary.toString();
}
Calling the method like formatSummary(data, 80, " "); will produce the output
Chicago, Il has zip codes: [60601, 60602, 60603, 60604, 60605, 60606, 60607, 60608,
60609, 60610, 60611, 60612, 60613, 60614, 60615, 60616, 60617, 60618, 60619, 60620,
60621, 60622, 60623, 60624, 60625, 60626, 60628, 60629, 60630, 60631, 60632, 60633,
60634, 60636, 60637, 60638, 60639, 60640, 60641, 60643, 60644, 60645, 60646, 60647,
60649, 60651, 60652, 60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60663,
60664, 60665, 60667, 60668, 60669, 60670, 60671, 60672, 60673, 60674, 60675, 60677,
60678, 60679, 60680, 60681, 60683, 60684, 60685, 60687, 60690, 60691, 60693, 60694,
60697, 60699, 60701]

How to use "write" to get the information in a for each loop

Im currently working on a project at school, where I am to switch out a certain word in an ArrayList. The word is written several times in the list. Im going to change it with a random word from a different ArrayList. My loop currently works as I wanted to, surly I can make it better, but it works atm. The word im changing is "ADJEKTIV"
My problem is that I cant get it to write to a file. It will print out using the System.out.println to terminal, but the assignment tell us to write it to the file.
public class StoryCreator
{
private InputReader reader;
private OutputWriter writer;
private Random random;
public StoryCreator()
{
reader = new InputReader();
writer = new OutputWriter();
random = new Random();
}
public void createAdjectiveStory(String storyFilename, String adjectivesFilename, String outputFilename)
{
ArrayList<String> storyWords = reader.getWordsInFileWithScanner(storyFilename);
ArrayList<String> adjectives = reader.getWordsInFileWithScanner(adjectivesFilename);
String replaceKeyword = "ADJEKTIV";
for(String words : storyWords)
{
if(storyWords.contains("ADJEKTIV"))
{
int adjectiveNumber = random.nextInt(adjectives.size());
String randAdjective = adjectives.get(adjectiveNumber);
String story = words.replace(replaceKeyword,randAdjective);
System.out.println(story);
writer.write(storyWords, outputFilename);
}
}
}
I've gotten the text to be written in a file, but it doesn't write the file where I have replaced the words I want. It writes the file before the words are changed.
The output writer class
public class OutputWriter
{
/**
* Constructor for objects of class OutputWriter
*/
public OutputWriter()
{
}
/**
* Writes a list of words to a file. The words are separated by the 'space' character.
*
* #param output the list of words
* #param filename the name of the output file
*/
public void write(ArrayList<String> output, String filename)
{
try {
FileWriter out = new FileWriter(filename);
for(String word : output) {
out.write(word + " ");
}
out.close();
}
catch(IOException exc) {
System.out.println("Error writing output file: " + exc);
}
}
}
Hope someone knows how I can manage this.
You are looping through String word : storyWords and replacing the word object with the random word. So, far so good.
The problem I think you have is here:
String story = words.replace(replaceKeyword,randAdjective);
System.out.println(story);
writer.write(storyWords, outputFilename);
You write out the story object using System.out.println(story) but then you write out the storyWords object to the file. This storyWords list will include the old String as you haven't replaced it with story (Which has the replacement in). This is why you are seeing the old word when writing to a file.
This brings up a new issue of the replacement of the String in storyWords as trying to modify within a for-each loop will throw an exception.
I think it would be better to use a normal for loop instead of a for-each to keep the position of the String inside storyWords so you can make the replace.
for(int i = 0 ; i < storyWords.size() ; i++)
{
String word = storyWords.get(i);
if(word.contains("ADJEKTIV"))
{
int adjectiveNumber = random.nextInt(adjectives.size());
String randAdjective = adjectives.get(adjectiveNumber);
String story = word.replace(replaceKeyword, randAdjective);
System.out.println(story);
storyWords.set(i, story);
writer.write(storyWords, outputFilename);
}
}
I think that should be the kind of thing you are looking for.
I have kept the code as close as possible to what you had originally written.
I did change the storyWords.contains("ADJEKTIV") to word.contains("ADJEKTIV") making the assumption that is what you meant.

reading in csv file and storing in arrays

the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks
You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}

How would I add a return statement for this, and how do I call the method?

public class InputFileData {
/**
* #param inputFile a file giving the data for an electronic
* equipment supplier’s product range
* #return an array of product details
* #throws IOException
*/
public static Product [] readProductDataFile(File inputFile) throws IOException {
// CODE GOES HERE (input data from a text file and sort into arraylists)
}
readProductDataFile is used to read a text file, and store it in an array of type Product[]. The code provided cannot be changed, I need a way that works with this code. I've managed to make file reading and sorting into array lists work in a different class, but running it in this way is giving me a couple of problems:
1) I can't call the readProductDataFile method from the Main class, as if it can't find the method (it's definitely in the correct package).
2) I can't figure out how to format the return statement, I've tried lots of different things but I just can't see how to store it as array type Product[].
I haven't provided a lot of specific code so far because I don't want the answer to be handed to me on a platter (this is part of an assignment so I don't want other people to straight up do it for me), but would anyone be able to point me in the right direction to solve this?
To give an idea of how I'm doing at the moment, the following test code worked for me:
ElectronicsEquipmentDemo class:
public class ElectronicsEquipmentDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Name inputFile = new Name();
inputFile.privateName();
}
}
Name class:
public class Name {
public String privateName() {
try {
FileReader fr = new FileReader("myOutput.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
char firstLetter = str.charAt(0);
if (firstLetter == 'P') {
String[] list = str.split("/");
Arrays.toString(list);
String fullName = list[1] + " " + list[2] + " " + list[3] + "\n";
System.out.println(fullName);
}
}
br.close();
} catch (IOException e) {
System.out.println("File not found");
}
return null;
}
}
Which reads from a text file and, if the line begins with P, splits into arrays and prints out specified values (although my attempt to add a return statement made it only return the first line, so still struggling there).
This should do it:
public class Name {
public String[] privateName(){
String[] list;
try {
FileReader fr = new FileReader("myOutput.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
char firstLetter = str.charAt(0);
if (firstLetter == 'P'){
list = str.split("/");
//Arrays.toString(list);
String fullName = list[1] + " " + list[2] + " "+ list[3] + "\n";
System.out.println(fullName);
}
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
return list;
}
}
Edit: fixed scoping issue.
Well, for the first problem, only thing I can notice is that your method is static, so be sure you're calling it correctly.
Also, consider if static is really what you want/need.
For the second problem, return list.toArray(new String[list.size()]) should work.

Java not detecting file contents

I'm having difficulty figuring out why this isn't working. Java simply isn't executing the while loop, file apparently does not have a next line.
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
Here is the file I am testing this with. I got it to work with the first few paragraphs but it seems to simply stop working...:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"
He took his vorpal sword in hand:
Long time the manxome foe he soughtó
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!
One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.
"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!"
He chortled in his joy.
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
——from Through the Looking-Glass, and What Alice Found There (1872).
/*
* Lab13a.java
*
* A program that prompts the user for an input file name and, if that file exists,
* displays each line of that file in reverse order.
* Used to practice simple File I/O and breaking code up into methods as well as a first
* step to implementing Lab13b.java - reversing the entire file and Lab13c.java writing
* output to a separate output file.
*
* #author Benjamin Meyer
*
*/
package osu.cse1223;
import java.io.*;
import java.util.*;
public class Lab13a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String fileName = "";
Scanner file;
boolean pass = false;
while (!pass) {
try {
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
}
catch (FileNotFoundException e) {
System.out.println("There was a problem reading from " + fileName);
System.out.println("Goodbye.");
return;
}
}
}
// Given a Scanner as input prompts the user to enter a file name. If given an
// empty line, respond with an error message until the user enters a non-empty line.
// Return the string to the calling program. Note that this method should NOT try
// to determine whether the file name is an actual file - it should just get a
// valid string from the user.
private static String getFileName(Scanner inScanner) {
boolean pass = true;
String fileName = "";
while (pass) {
System.out.print("Enter an input name: ");
fileName = inScanner.nextLine();
if (fileName.length()!=0) {
pass = false;
}
else {
System.out.println("You cannot enter an empty string.");
}
}
return fileName;
}
// Given a String as input return the reverse of that String to the calling program.
private static String reverse(String inString) {
if (inString.length()==0) {
return "";
}
String reversed = "" + inString.charAt(inString.length()-1);
for (int x = inString.length()-2; x>=0; x--) {
reversed = reversed + inString.charAt(x);
}
return reversed;
}
}
The issue might lie in your implementation of your functions getFilename() or reverse(). Since you have stated that you got it to work with a few of the paragraphs I doubt that your program is failing due to your file handling. It might be in the logic you are using to reverse the strings in the file that is causing the issue.

Categories

Resources