So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();
Related
I'm trying to create a class that sorts an array list in descending order of marks. As all my methods are static, I want to write a constructor to prevent class instantiation but am not sure how to go about doing it. I read that a private constructor can be used but unsure how to go about coding it.
Here's my code:
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
PrintStream out = null;
try
{
out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Static methods belong to the class. I don't really understand why are you worrying about having/not having class instantiation. whether they create one instance or multiple instance the callers will have the same copy of static method.Having said that, You can still limit instantation outside the class by adding a default private constructor like below
private ProcessDegreeMark(){}
Just add private modifier before constructor.
public class ProcessDegreeMark{
private ProcessDegreeMark(){}
}
Here, I wrote my code with my output. I do not know about how to work with duplicate records.
class Price{
int productID,totalSold=0,totalPrice=0;
double price;
public Price(int productID,double price) {
this.price= price;
this.productID=productID;
}
}
class Slips{
int personID, productID, numberOfSold,product1Sold,product2Sold,product3Sold,product4Sold,performance;
public Slips(int personID,int productID,int numberOfSold)
{
this.personID=personID;
this.productID=productID;
this.numberOfSold=numberOfSold;
}
}
class PriceComparator implements Comparator<Price>{
public int compare(Price p1,Price p2)
{
return Integer.compare(p2.totalPrice, p1.totalPrice);
}
}
public class PTestDec2009 {
static ArrayList<Price> ALPrice=new ArrayList<>();
static ArrayList<Slips> ALSlips=new ArrayList<>();
public static void main(String[] args) throws FileNotFoundException, IOException {
getPriceInfo("C:\\Users\\Mayank Patel\\Documents\\NetBeansProjects\\PTestDec2009\\src\\ptestdec2009\\price.txt");
getSlipsInfo("C:\\Users\\Mayank Patel\\Documents\\NetBeansProjects\\PTestDec2009\\src\\ptestdec2009\\slips.txt");
updateSalability();
updateSalesPersonPerformance();
}
private static void getPriceInfo(String fileName) throws FileNotFoundException, IOException {
String line=null;
BufferedReader bufferReader=new BufferedReader(new FileReader(fileName));
while((line=bufferReader.readLine())!=null)
{
StringTokenizer tokenizer=new StringTokenizer(line);
while(tokenizer.hasMoreTokens())
{
ALPrice.add(new Price(Integer.parseInt(tokenizer.nextToken()),Double.parseDouble(tokenizer.nextToken())));
}
}
}
private static void getSlipsInfo(String fileName) throws FileNotFoundException, IOException {
String line=null;
BufferedReader bufferReader= new BufferedReader(new FileReader(fileName));
while((line=bufferReader.readLine())!=null)
{
StringTokenizer tokenizer=new StringTokenizer(line);
while(tokenizer.hasMoreTokens())
{
ALSlips.add(new Slips(Integer.parseInt(tokenizer.nextToken()),Integer.parseInt(tokenizer.nextToken()), Integer.parseInt(tokenizer.nextToken())));
//updateSalesPersonPerformance(Integer.parseInt(tokenizer.nextToken()),Integer.parseInt(tokenizer.nextToken()), Integer.parseInt(tokenizer.nextToken()));
}
}
}
private static void updateSalesPersonPerformance()
{
for(int plooper=0;plooper<ALPrice.size();plooper++)
{
for(int slooper=0;slooper<ALSlips.size();slooper++)
{
if(ALPrice.get(plooper).productID == ALSlips.get(slooper).productID)
{
switch (ALSlips.get(slooper).productID) {
case 1:
ALSlips.get(slooper).product1Sold += ALSlips.get(slooper).numberOfSold;
break;
case 2:
ALSlips.get(slooper).product2Sold += ALSlips.get(slooper).numberOfSold;
break;
case 3:
ALSlips.get(slooper).product3Sold += ALSlips.get(slooper).numberOfSold;
break;
case 4:
ALSlips.get(slooper).product4Sold += ALSlips.get(slooper).numberOfSold;
break;
default:
break;
}
ALSlips.get(slooper).performance += ALPrice.get(plooper).price* ALSlips.get(slooper).numberOfSold;
}
}
}
System.out.println("\nPERSONID"+"\t"+"PRODUCT1"+"\t"+"PRODUCT2"+"\t"+"PRODUCT3"+"\t"+"PRODUCT4"+"\t"+"PERFORMANCE");
for(int slooper=0;slooper<ALSlips.size();slooper++)
{
System.out.println(ALSlips.get(slooper).personID+"\t\t"+ALSlips.get(slooper).product1Sold+"\t\t"+ALSlips.get(slooper).product2Sold+"\t\t"+ALSlips.get(slooper).product3Sold+"\t\t"+ALSlips.get(slooper).product4Sold+"\t\t"+ALSlips.get(slooper).performance);
}
}
private static void updateSalability() {
for(int plooper=0;plooper<ALPrice.size();plooper++)
{
for(int slooper=0;slooper<ALSlips.size();slooper++)
{
if(ALPrice.get(plooper).productID == ALSlips.get(slooper).productID)
{
ALPrice.get(plooper).totalSold += ALSlips.get(slooper).numberOfSold;
ALPrice.get(plooper).totalPrice += ALPrice.get(plooper).price * ALSlips.get(slooper).numberOfSold;
}
}
}
Collections.sort(ALPrice,new PriceComparator());
System.out.println("PRODUCTID"+"\t"+"TotalSold"+"\t"+"TotalPrice");
for(int plooper=0;plooper<ALPrice.size();plooper++)
{
System.out.println(ALPrice.get(plooper).productID+"\t\t"+ALPrice.get(plooper).totalSold+"\t\t"+ALPrice.get(plooper).totalPrice);
}
}
}
so please help me to get my expected output. I attached image file with my output and expected output.
Thanks in advance.
just use this:
public static void removeDuplicates(){
ArrayList<Slips> newRay = new ArrayList<Slips>();
for(Slips s : ALSlips){
boolean hasAlready = false;
for(Slips d: newRay){
if(d.personID == s.personID){
d.product1Sold += s.product1Sold;
d.product2Sold += s.product2Sold;
d.product3Sold += s.product3Sold;
d.product4Sold += s.product4Sold;
d.numberOfSold += s.numberOfSold;
d.performance += s.performance;
hasAlready = true;
}
}
if(!hasAlready){
newRay.add(s);
}
}
ALSlips = newRay;
}
I beg of you though, please rewrite this, or comment it, or something!! unless you are doing this for your job. then leave it how it is. they won't be able to fire you.
If you want to eliminate duplicates you can use either set or hashset instead of arraylist but if your stuffing an object into a collection you need to override equals method so that you hashset treats object as duplicate based on some attribute rather than its address for example overriden equals for your problem can be
#Override
public String eqauls(Slips s)
{
if(this.personId==s.personId)
return true;
else
return false;
}
this should be placed in your slips class.
I am not completely clear about your requirement but this is how you can eliminate duplicates
Rather than use an ArrayList use a HashMap or a HashSet
The key to this Map would be the String PRODUCTID
presently you are adding to an ArrayList, but if you put to your HashMap, you can try to get it first. If it exists, you can update the value in it.
An example would be something like
HashMap myMap <String, Price val> = new HashMap <> ();
Price newPrice = ....; // like your existing code
String prodid = newPrice.getProductId ();
Price oldVal = myMap.get (prodid);
if (oldVal != null) {
// update newPrice with sum of val
}
myMap.put (prodid, newPrice); // will add or replace
My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {
I'm doing a project for a class, but for the life of me I'm having the hardest time figuring out how to read text from a file. We have to create a traffic light that queues trucks and cars coming from North, South, East, and West. It's been a long time since I've done any coding, so I'm struggling immensely. I think it just reads the memory location. Here's my code for reading in a file.
package Project1;
import java.io.*;
import java.util.*;
public class TrafficSim {
public String input;
public TrafficSim(String input)
{
this.input = input;
readFromFile();
}
private boolean readFromFile()
{
File inputText = new File("input1.txt");
try
{
Scanner scan = new Scanner(inputText);
while(scan.hasNextLine())
{
String direction = scan.nextLine();
int num = scan.nextInt();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim);
}
}
Your method readFromFile sure enough reads from a file, but then it doesn't do anything. All you do is read line by line, storing a line of text and an int in variables which are forgotten after each iteration of your while loop.
Your code System.out.println(sim) prints out whatever the toString method of your class returns, and since you didn't override that method it will print out the result of Object.toString, which is not what you want.
To put it simply, you're reading from a file but you're not doing anything with the contents that you read.
Here is what I would do....
public class TrafficSim {
private String input;
private String content;
public TrafficSim(String input) {
this.setInput(input);
this.setContent(readFromFile());
}
private String readFromFile() {
File inputText = new File(input);
StringBuilder sb = new StringBuilder();
try {
Scanner scan = new Scanner(inputText);
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public static void main(String[] args) {
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim.getContent());
}
}
The issue I see though is that you're not following the comments and suggestions already made. ktm5124 was pretty clear on what the problem is. At some point you're going to have to understand what is going on here and how to fix it.
i have created string arraylist in which i copied all the data from database. Then i removed one record from arraylist by using al.remove(1, null). Now i want to add record in the position on which there is no data. I mean i want to add data at the position where data is null. I did write al.set(position, "new") but its giving me run time error i.e. OutOfMemory. Pls help me. Thanks
import java.io.*;
import java.util.*;
public class DAOImpl implements DAO
{
String xs[];
List<String> al= new ArrayList<String>();
int value;
public void list()
{
try
{
BufferedReader br=new BufferedReader(new FileReader("insurance.db"));
String next;
while((next=br.readLine())!=null)
{
//System.out.println(next);
al.add(next);
}
for(int i=0;i<al.size();i++)
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
//System.out.println(al.get(i));
System.out.println("");
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public String[] readRecord(int recNo)
{
String stream=(al.get(x-1));
xs=stream.split(":");
return xs;
}
public void deleteRecord(int recNo)
{
int del=recNo;
al.set(del-1, null);
for(int i=0;i<al.size();i++)
{
if((al.get(i))==null)
{
continue;
}
else
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
System.out.println("");
}
}
}
public int addRecord()
{
for(int y=0;y<al.size();y++)
{
if((al.get(y))==null)
{
value=y+1;
}
if((al.get(y))==null)
{
al.add(y, "new");//m getting error here...
}
}
for(int i=0;i<al.size();i++)
{
if((al.get(i))==null)
{
continue;
}
else
{
System.out.print(i+1+"] ");
String ar[]=(al.get(i)).split(":");
for(int q=0;q<3;q++)
{
System.out.print(ar[q]);
System.out.print(" ");
}
System.out.println("");
}
}
return value;
}
}
and main method is as follow:
import java.io.*;
public class InsuranceMain
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DAOImpl d=new DAOImpl();
d.list();
//deleterecord
System.out.println("Enter Record Number to delete record:");
int delete=Integer.parseInt(br.readLine());
d.deleteRecord(delete);
//addrecord
d.addRecord();//m getting error here
//readRecord
System.out.println("Enter Record Number:");
int s=Integer.parseInt(br.readLine());
String as[]=d.readRecord(s);
for(int v=0;v<as.length;v++)
{
System.out.println(as[v]);
}
}
}
short answer:
change this line:
al.add(y, "new");//m getting error here...
into
al.set(y, "new");
Reason:
if you al.add(y,"new"), then, all elements after y (inclusive) will be shifted right. So next time you meet the null again (y+1), you add another "new", do this loop no ending.
also it is not good if you changing the list's size within a for loop like this.