Populate DefaultTableModel from test file - java

I have this text file:
A
B
3.00
A
B
3.00
and my view is:
I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

you can do this as there is an blank line in your input file .
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
if(line.isEmpty())
continue;
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}

Your counter is incrementing at the begining of loop, so you never have 0 but 1 on if statement. Then empty line is parsed as 1 and goes to A column. You can solve it in multpile ways like skip empty lines or increment counter if line is not empty.

Related

Accessing indexes that may not exist Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code

reading a file in java and controlling an array list

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.

Would there be a cleaner/better way to write this

The code is suppose to read information from a file, create a object using that information, and then adding it to an ArrayList called servers.
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line = "";
while ((line = br.readLine()) != null) {
String name = "";
String ip = "";
String port = "";
String checkFrequency = "";
int counter = 1;
boolean alert = true;
for (String value : line.split(",")){
if (counter == 1){
name = value;
}else if (counter == 2){
ip = value;
}else if (counter == 3){
port = value;
}else if (counter == 4){
checkFrequency = value;
}else if (counter == 5){
alert = Boolean.parseBoolean(value);
}
counter++;
}
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Example line of what is stored in file:
Name,199.99.99.99,80,60,true
Would there be a better way to retrieve that information to be able to store it in the correct variable without using a loop with a counter the way shown above?
What about:
try (BufferedReader br = new BufferedReader(
new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)))) {
String line = null; // start with null in case there is no line
while ((line = br.readLine()) != null) {
String[] tokens = line.split(",");
MCServer server =
new MCServer(tokens[0], tokens[1], tokens[2], tokens[3],
Boolean.parseBoolean(tokens[4]));
servers.add(server);
}
}
You can just ignore the counter and use directly the tokens, but you should at least be sure there are enough tokens:
try
{
BufferedReader br = new BufferedReader(new InputStreamReader());
String line = null;
String[] tokens;
while ((line = br.readLine()) != null) {
tokens = line.split(",");
MCServer test = new MCServer(tokens[0],tokens[1],tokens[2],tokens[3],Boolean.valueOf(tokens[4]));
}
}
catch (IndexOutOfBoundsException e) { // <- be sure to catch this
// not enough elements in array
}
In addition you are passing strings as IP addresses and port, they are string but they should be checked against being convertible, so you could have Integer.valueOf(tokens[2]) for example just to raise a NumberFormatException in case.
Try this
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line = "";
while ((line = br.readLine()) != null) {
String name = "";
String ip = "";
String port = "";
String checkFrequency = "";
int counter = 1;
boolean alert = true;
String s[] = line.split(",");
name = s[0];
ip = s[1];
port = s[2];
checkFrequency= s[3];
alert = s[4];
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I've revised your code a bit:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line;
while ((line = br.readLine()) != null) {
String[] lineSplitted = line.split(",");
String name = lineSplitted[0];
String ip = lineSplitted[1];
String port = lineSplitted[2];
String checkFrequency = lineSplitted[3];
boolean alert = Boolean.parseBoolean(lineSplitted[4]);
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Changes:
initialising the variables and then setting them is redundant, you never access them without setting them beforehand, so if you have your line splitted in the the first place you can initialise them with the values right away
for cycle is unnecessary if you're working with a single array each time, just access the correct elements of the array
catch blocks can be collapsed; IOException covers FileNotFoundException

Null Pointer Exception Occurs only while comparison and not printing out values

public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
BufferedReader in1 = new BufferedReader(new FileReader("595231gov_nov_13_assessed.txt"));
BufferedReader in2 = new BufferedReader(new FileReader("627231farsidetect.txt"));
String Id = null;
int count = 0;
String count_line=null;
while((count_line = in1.readLine()) != null){
if(count_line.contains("ID: "))
count ++;
}
System.out.println(count);
File1 [] File_1 = new File1[count];
in1 = new BufferedReader(new FileReader("595231gov_nov_13_assessed.txt"));
int i = 0;
String line = null;
String relation = null;
while ((line = in1.readLine()) != null && i != count){
if(line.contains("ID:")){
File_1 [i] = new File1();
File_1[i].ID = line;
}
else if(line.contains("Relation:")){
File_1[i].Relation = line;
}
else if(line.contains("Result:")){
File_1[i].Result = line;
i ++;
}
else if(line.contains("TP") || line.contains("FP") || line.contains("TN") || line.contains("FN")){
File_1[i-1].Comment = line;
}
}
line = null;
relation = null;
i =0;
int count2 = 0;
count_line=null;
while((count_line = in2.readLine()) != null){
if(count_line.contains("ID: "))
count2 ++;
}
System.out.println(count2);
in2 = new BufferedReader(new FileReader("/home/627231farsidetect.txt"));
File2 [] File_2 = new File2[count2];
while ((line = in2.readLine()) != null && i != count2){
if(line.contains("ID:")){
File_2 [i] = new File2();
File_2[i].ID = line;
}
else if(line.contains("Relation:")){
File_2[i].Relation = line;
}
else if(line.contains("Result:")){
File_2[i].Result = line;
i ++;
}
}
in1.close();
in2.close();
for (i=0; i<File_1.length - 1; i++)
{
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
for (i=0; i<File_2.length; i++)
{
System.out.println(File_2[i].ID);
System.out.println(File_2[i].Relation);
System.out.println(File_2[i].Result);
}
for (i = 0; i < File_1.length-1; i++){
for(int j=0;j< File_2.length; i++){
if(File_1[i].ID != null && File_2[j].ID != null && File_1[i].Relation != null && File_2[j].Relation !=null){
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation)){
if(!(File_1[i].Result.equals(File_2[j].Result))){
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
}
}
}
}
}
public static class File1{
public String ID;
public String Relation;
public String Result;
public String Comment;
public File1() {
this.Result = null;
this.ID=null;
this.Relation = null;
this.Comment = null;
}
}
public static class File2{
public String ID;
public String Relation;
public String Result;
public File2() {
this.Result = null;
this.ID=null;
this.Relation = null;
}
}
-When I just printout the values, I do not face a null pointer exception,
-But when I try and do comparison I am faced with a null pointer exception and I can't figure out why.
-NetBeans just points to the comparison statement
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation))
Something else which is unusual is that, I have assigned values for File_1 until File_1[Length] but it prints out length - 1 values. Whereas I assigned values for File_2 the same way and it prints fine. Please help. I am processing Farsi text, so there might be the possibility of weird characters, but I am pretty sure there has to be something to do with the index values.
Don't know if it was intentional or not, but in your for loop you seem to be incrementing the wrong value (i instead of j)...
for (i = 0; i < File_1.length-1; i++)
{
for(int j=0;j< File_2.length; j++)
{
if(File_1[i].ID != null && File_2[j].ID != null && File_1[i].Relation != null && File_2[j].Relation !=null)
{
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation))
{
if(!(File_1[i].Result.equals(File_2[j].Result)))
{
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
}
}
}
}

Java Code check fields in duplicate, when value change start again

I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0

Categories

Resources