I know my code is not optimal and there is certainly a better way to write what I am trying to do than how I have it written.
I am trying to setup a reader so that it inserts information into an array list. Right now my problem is that I cannot find out how to add an object to an array list only once. The last object of the file is filling the empty spaces of the arrayList.
public void readCharacterFile() {
String fileName = "C:/Users/brenton.reittinger/Desktop/characters.txt";
String line = null;
String fileContent = "";
try {
FileReader in = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(in);
while((line = bufferReader.readLine()) != null) {
fileContent = fileContent + line;
}
bufferReader.close();
} catch(Exception e){
e.printStackTrace();
}
Character character = new Character();
Attributes attribute = new Attributes();
character.setAttribute(attribute);
String[] file = fileContent.split(":");
int count = 0;
for (String fileSection : file) {
if (fileSection.length() > 0) {
if(count == 5) {
character.getAttribute().setLevel(Integer.parseInt(fileSection));
count++;
}
if(count == 4) {
character.getAttribute().setExperience(Integer.parseInt(fileSection));
count++;
}
if(count == 3) {
character.getAttribute().setHealth(Integer.parseInt(fileSection));
count++;
}
if(count == 2) {
character.getAttribute().setAttack(Integer.parseInt(fileSection));
count++;
}
if(count == 1) {
character.setRace(fileSection);
count++;
}
if(count == 0) {
character.setName(fileSection);
count++;
}
}
}
user.addCharacterToList(character);
}
Why not using a java Set instead? Sets guarantee that each object instance can only occur once.
Related
I am able to convert my csv file into an arraylist, but I want to be able to find the mean and standard deviation of each row in my arraylist. I would like to do this by converting each row to an individual array to be able to call for future use.
BufferedReader gradeBuffer = null;
try {
String gradeLine;
gradeBuffer = new BufferedReader(new FileReader("Assignment4-datafile.csv"));
// Read in file line by line
while ((gradeLine = gradeBuffer.readLine()) != null) {
System.out.println(gradeCSVtoArrayList(gradeLine));
}
//throw exception if file not found
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (gradeBuffer != null) gradeBuffer.close();
} catch (IOException gradeException) {
gradeException.printStackTrace();
}
}
}
// Convert CSV to ArrayList using Split
public static ArrayList<String> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<String> gradeResult = new ArrayList<String>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(splitData[i].trim());
}
}
}
return gradeResult;
}
}
I think the first thing that you need to do is change gradeCSVtoArrayList to return a List of numbers, either Long or Double depending on if it is integer or floating point numbers.
public static ArrayList<Long> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<Long> gradeResult = new ArrayList<Long>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(Long.parseLong(splitData[i].trim()));
}
}
}
return gradeResult;
}
WIth this list you can find mean and standard deviation.
I have two methods, both using FileInputStream Objects.
The First one returns expected value. This method works fine.
But the Second method returns nothing. The value passed to the second method is not null.
I need to get the hexadecimal format of the files passed to methods.
Why is it so? Kindly Explain.
Here is my code
public String binaryFile1(File file1){
try{
stringBuilder1=new StringBuilder();
is1=new FileInputStream(file1);
while(b!=-1){
counter++;
b=is1.read();
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
stringBuilder1.append('0');
}
if(counter%5==0){
stringBuilder1.append(s).append("\n");
counter=0;
}else
stringBuilder1.append(s).append(' ');
}
is1.close();
}catch(Exception e){
e.printStackTrace();
}
return stringBuilder1.toString();
}
public String binaryFile2(File file2){
try{
stringBuilder2=new StringBuilder();
is2=new FileInputStream(file2);
while(b!=-1){
counter++;
b=is2.read(); //Here b does not get any content assigned.
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
stringBuilder2.append('0');
}
if(counter%5==0){
stringBuilder2.append(s).append("\n");
counter=0;
}else
stringBuilder2.append(s).append(' ');
}
is2.close();
}catch(Exception e){
e.printStackTrace();
}
return stringBuilder2.toString(); //Here stringBuilder2 is null
}
Since b is shared and you don't reset it after binaryFile1 it's still -1 at the start of binaryFile2. I suggest you use,
int b;
while ((b = is2.read()) != -1) {
// ...
}
Edit
It is important to close your resources when you're done. I also suggest you try and limit variable scope as much as possible. Using try-with-resources you could write binaryFile2 like
public String binaryFile2(File file) {
StringBuilder sb = new StringBuilder();
int counter = 0;
try (InputStream is = new FileInputStream(file)) {
int b;
while ((b = is.read()) != -1) {
counter++;
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
if (counter % 5 == 0) {
sb.append(System.lineSeparator());
counter = 0;
} else {
sb.append(' ');
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I have a text file with a maximum of 4 lines to read from. Each line has a mixture of strings and integers spaced out by tabs.
I have successfully made my program read 1 line and store all the information in the appropriate spot, while also storing a new object in the array.
The problem: I can't figure out how to get it to read multiple lines while also storing a new object in the array depending on the line read.
Here is my method that takes the file and and stores an object in the array:
public void addVehicle(Vehicle Honda[]) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length; i++)
{
if(vehicles[i] == null)
{
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
break;
}
}
System.out.println("Vehicle Added!");
}
else
{
System.out.println("You can not add more than 4 vehicles.");
}
}
And the readRecord() method:
public void readRecord(Scanner reader)
{
while(reader.hasNextLine())
{
setMake(reader.next());
setModel(reader.next());
setYear(reader.nextInt());
setvin(reader.next());
setValue(reader.nextDouble());
setMilesDriven(reader.nextInt());
setLastOilChange(reader.nextInt());
}
reader.close();
}
If you can only successfully store one Vehicle instance, it's because your closing the reader too soon.
In addVehicle(), get rid of
reader.close();
and in readRecord(), get rid of
reader.close();
Close the reader at the end of addVehicle().
Finally fixed my problem!
public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
boolean found = false;
int position = 0;
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length && !found; i++)
{
if(vehicles[i] == null)
{
position = i;
found = true;
}
}
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
Honda[position] = new Vehicle();
Honda[position].readRecord(reader);
vehicles[position] = Honda[position];
position++;
}
reader.close();
return true;
}
return false;
}
I am beginner with Java.
This is my approach:
I am trying to read two files and then get the union of them. I should am using an array with size 100. (just one array allowed, reading and writing line by line or arrayList or other structures are not allowed.)
First, I read all records from file1, and write them to the output, a third file. For that purpose, I read 100 record at a time, and write them to the third file using iteration.
After that, like first file, this time I read second file as 100 records at a time, and write them to the memory[]. Then I find the common records, if the record which I read from File2 is not in File1, I write it to the output file. I do this until reader2.readLine() gets null and I re-open file1 in each iteration.
This is what I have done so far, almost done. Any help would be appreciated.
Edit: ok, now it doesn't give any exception, but it can't find the different records and can't write them. I guess the last for loop and booleans don't work , why? I really need help. Thanks for your patience.
import java.io.*;
public class FileUnion
{
private static long startTime, endTime;
public static void main(String[] args) throws IOException
{
System.out.println("PROCESSING...");
reset();
startTimer();
String[] memory = new String[100];
int memorySize = memory.length;
File file1 = new File("stdlist1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
File file3 = new File("union.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file3));
int numberOfLinesFile1 = 0;
String line1 = null;
String line11 = null;
while((line1 = reader1.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line1;
i++;
if(i < memorySize)
{
line1 = reader1.readLine();
}
}
for (int i = 0; i < memorySize; i++)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
reader1.close();
File file2 = new File("stdlist2.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line2 = null;
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
line2 = reader2.readLine();
}
}
for (int k = 0; k < memorySize; k++ )
{
boolean found = false;
File f1 = new File("stdlist1.txt");
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for (int m = 0; m < numberOfLinesFile1; m++)
{
line11 = buff1.readLine();
if (line11.equals(memory[k]) && found == false);
{
found = true;
}
}
buff1.close();
if (found == false)
{
writer.write(memory[k]);
writer.newLine();
}
}
}
reader2.close();
writer.close();
endTimer();
long time = duration();
System.out.println("PROCESS COMPLETED SUCCESSFULLY");
System.out.println("Duration: " + time + " ms");
}
public static void startTimer()
{
startTime = System.currentTimeMillis();
}
public static void endTimer()
{
endTime = System.currentTimeMillis();
}
public static long duration()
{
return endTime - startTime;
}
public static void reset()
{
startTime = 0;
endTime = 0;
}
}
EDIT! Redo.
Ok, so to use 100 lines at a time you need to check for null, otherwise trying to write null to a file could cause errors.
You are checking if the file is at the end once, and then gathering 99 more peices of info without checking for null.
What if when this line is called:
while((line2 = reader2.readLine()) != null)
there is only 1 line left in the file? Then your memory array contains 99 instances of null, and you try to write null to the file 99 times. That's worse case scenario.
I don't really know how much help we are supposed to give to people looking for homework help, on most sites I'm familiar with it's not even allowed.
here is an example of one way to write the first file.
String line1 = reader1.readLine();
boolean end_of_file1 = false;
while(!end_of_file)
{
for (int i = 0; i < memorySize)
{
memory[i] = line1;
i++;
if(i < memorySize)
{
if((line1 = reader1.readLine()) == null)
{
end_of_file1 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
}
reader1.close();
once you have that, to make the checking for copies easier, make a public static boolean that checks the file for it, then you can call that, it will make the code cleaner.
public static boolean isUsed(String f1, String item, int dist)
{
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for(int i = 0;i<dist;i++)
{
String line = buff1.readLine()
if(line == null){
return false;
}
if(line.equals(item))
{
return true;
}
}
return false;
}
Then use the same method as writing file 1, only before writing each line check to see if !isUsed()
boolean end_of_file2 = false;
memory = new String[memorySize];// Reset the memory, erase old data from file1
int numberOfLinesFile2=0;
String line2 = reader2.readLine();
while(!end_of_file2)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
if((line2 = reader2.readLine()) == null)
{
end_of_file2 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
//Check is current item was used in file 1.
if(!isUsed(file1, memory[i], numberOfLinesFile1)){//If not used already
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile2++;
}
}
}
}
reader2.close();
writer.close();
Hope this helps. Notice I'm not supplying the full code, because I've learned that just pasting the code will make it more likely for copy and paste to just use a code without understanding it. I hope you find it useful.
I'm having trouble using the Java JFileChooser and was wondering if anyone could help me out. It's probably something really simple but I just can't spot what's wrong.
The JFileChooser window opens fine when I click my import button and I can navigate to any field but I just cant read them into my JTextFields.
Heres my JFileChooser method:
public void importFile() {
JFileChooser chooser = new JFileChooser();//A
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //a
try {
BufferedReader file_in = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath()));
int i = 0;
String name = "",hnumber = "", mnumber = "", address = "";
while (((fileLines = file_in.readLine()) != null)) {
if (fileLines.length() > 0) {
i++;
if (i == 1) {
name = fileLines;
} else if (i == 2) {
hnumber = fileLines;
} else if (i == 3) {
mnumber = fileLines;
} else if (i == 4) {
address = fileLines;
String[] nameArray = name.split(" ");
Contact c = new Contact (nameArray[1], nameArray[0],
hnumber, mnumber, address);
contactList.add(c);
index = 0;
}
}
}
for (int j = 0; j < contactList.size(); j++) {
System.out.print(contactList.get(j).getname());
System.out.print(" ");
System.out.println(contactList.get(j).getmnumber());
System.out.println(contactList.get(j).gethnumber());
System.out.println(contactList.get(j).getaddress());
System.out.println(contactList.get(j).getsurname());
System.out.println(" ");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
You should use a List or a StringBuilder for ease of getting the lines. And do you get any error(s) as result? Debugging would really help to see where your program is breaking.
Here is something I put together for you real quick:
public void importFile() {
JFileChooser chooser = new JFileChooser();//A
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //a
try {
FileReader fr = new FileReader(chooser.getSelectedFile().getPath());
BufferedReader file_in = new BufferedReader(fr);
List lines = new List();
String line = new String("");
while ((line = file_in.readLine()) != null) {
list.add(line);
if (list.size() >= 3) {
String[] nameArray = ((String)list.get(0)).split(" ");
Contact c = new Contact (nameArray[1], nameArray[0],
(String)list.get(1), (String)list.get(2),
(String)list.get(3));
contactList.add(c);
}
System.out.println(list.get(list.size()-1)); // Debug
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
I didn't compile it so may have some typos or of such...
It imports into a array list called "contactList" which you can see is on the 5th line from the bottom. So it doesn't go straight into the JTextFields but either way I can't get it to work.