I've created this class along with the linkedlist class and they are in the same folder. The input appears to work fine besides the fact that the runner class won't output anything, even when I enter p into the command prompt. Even when I encapsulate the methods in System.out.print, nothing happens.
Runner class
public class runner{
static String s;
public static void main(String[] args) throws java.io.IOException{
linkedlist link= new linkedlist();
System.out.println("Type a command\n");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try{
s=in.readLine();
char first=s.charAt(0);
while(in.readLine()!=null){
s=in.readLine();
int space= s.indexOf(" ");
if(first=='i'){
String w=s.substring(space);
link.insert(w);
}
if(first=='d'){
String w=s.substring(space);
link.delete(w);
}
if(first=='f'){
String w=s.substring(space);
link.find(w);
link.find(w);
}
if(first== 'p'){
link.printlist();
}
}
}catch(Exception e) {
System.out.println("Ack!: " + e);
}finally{
in.close();
}
}
}
Linked List class
import java.io.*;
public class linkedlist{
node head;
public linkedlist(){
head=null;
}
public void insert(String s){
head= new node(s,head);
}
public void printlist(){
node i= head;
while(i.getData(i)!=null){
System.out.print(i.getData(i));
i=i.getNext();
}
}
public String find(String s){
String comp=head.getData(head);
node ref=head.getNext();
String check=ref.getData(ref);
String temp=check;
while(check != "null"){
if(s.equals(check)){
head=ref;
ref=head.getNext();
check=ref.getData(ref);
}
else{
temp=check;
}
}
return temp;
}
public String delete(String s){
String comp=head.getData(head);
node ref=head.getNext();
String check= ref.getData(ref);
node ref2= ref.getNext();
String post=ref2.getData(ref2);
String temp=check;
while(check != "null"){
if(s.equals(check)){
ref=ref2;
}
else{
comp=check;
ref=head.getNext();
check=ref.getData(ref);
ref2= ref.getNext();
post=ref2.getData(ref2);
}
}
return temp;
}
}
I guess it happens because you are swallowing several input lines here:
try{
s=in.readLine(); //you consume one line here
char first=s.charAt(0);
while(in.readLine()!=null){ //you consume another here
s=in.readLine(); //and another one..
replace it with:
while ((s = in.readLine()) != null) { // while loop begins here
char first=s.charAt(0);
[...]
} // end while
Related
I have a code that reads an id block of three lines from a text file, I want to split those lines in Strings and an int, and pass this to a constructor from another class.
Right now, this class asks for an id number and prints everything below the # sign, down to and including the third line of each id block. I want those three lines in each id to be parsed as 'name', 'age' and 'job' to an Employee class, in order to create an object of the id, like this: Employee("Richard Smith",22,"Electric engineer"). There will always be three lines in the file for an id, so how can I "find" those lines and split them into Strings and an int?
#1000
Richard Smith
22
Electric engineer
#1001
Elliot Smith
23
Physicist
public class RdB
{
String b; //file name
RdB(String ename) {
b = ename;
}
//info about an employee
boolean showE (String id) {
int ch;
String code, info;
//open the file with the info
try (BufferedReader showERdr =
new BufferedReader (new FileReader(b)))
{
do {
//read characters until a '#' is found
ch = showERdr.read();
//check
if(ch == '#') {
code = showERdr.readLine();
if(id.compareTo(code) == 0) { //found employee
do {
info = showERdr.readLine();
if(info != null) {
System.out.println(info);
}
} while(((info != null) &&
(info.compareTo("") != 0)));
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
System.out.println("File error!");
return false;
}
return false; //employee not found
}
//Access a registered employee
String getE() {
String id = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter id number: ");
try{
id = br.readLine();
}
catch(IOException exc) {
System.out.println("Access error");
}
return id;
}
}
Edit:
Employee class
class Employee {
private String name, job;
private int age;
public Employee (String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getJob () {
return job;
}
}
You can simply use an ArrayList to save what you read from the file and process it later. Since you are certain about the features of your saved file that it will always contain 3 lines before the line which contains ID, here is the working code I wrote to solve your problem. You can see the output wrapped between ( )
Here is the code:
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class Emp{
public static void main(String[] args) throws IOException{
List data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("PeopleData.txt"));
String str;
while((str = reader.readLine()) != null){
// System.out.println(str);
data.add(str);
}
for(int i= 0; i< data.size(); i ++){
i++;
System.out.println("(");
System.out.println(data.get(i));
String name = (String) data.get(i);
i++;
System.out.println(data.get(i));
int age = Integer.valueOf((String) data.get(i));
i++;
System.out.println(data.get(i));
String job = (String) data.get(i);
i++;
System.out.println(")");
//new Employee(name, age, job);
}
}
}
I am making a class in java to parse in CSV's. It will read in the file line by line and parse out each field according to the regex pattern into an array, and then print that array. I put all this together in a main driver below. I looked over everything and it seems to be functional but for some reason whenever I run it, it just gets stuck in an infinite loop and will not cease. I have looked over this many times and can just not find where this would happen. Any help with this issue would be greatly appreciated!
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Pattern;
/**
*
*/
public class Csv {
private FileInputStream fin;
private String line;
private String[] parsedFields;
public boolean isEOL(char n) {
boolean eol;
if (n == '\n' || n == '\r') {
eol = true;
}
else
eol=false;
return eol;
}
public String getLine()
{
try
{
char c;
c= (char) fin.read();
while(!isEOL(c))
{
line+=c;
}
}
catch (IOException e) {
System.out.println("Input Error.");
}
return line;
}
public void parseFields(String s)
{
Pattern CSVLine=Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
parsedFields=CSVLine.split(s);
}
public void execute()
{
String field=getLine();
parseFields(field);
}
public void setFin(FileInputStream usrFin)
{
fin=usrFin;
}
public void outputFields()
{
for(int i=0; i<parsedFields.length;i++)
{
System.out.println(parsedFields[i]);
}
}
public static void main(String args[])
{
try {
FileInputStream fis;
fis = new FileInputStream("test.txt");
Csv test= new Csv();
test.setFin(fis);
test.execute();
test.outputFields();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
c= (char) fin.read();
while(!isEOL(c))
{
line+=c;
}
In this part, you loop, adding c, but you never read again. c never changes during the loop, and probably is stuck there. You need to have the c = fin.read(); inside the loop too.
public static List<String> readLine(String filePath){
List<String> listStr = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
Pattern pat = Pattern.compile(LINE_PATTERN_REGEXP);
while((line=br.readLine())!=null){
Matcher matcher = pat.matcher(line);
if(!matcher.find()){
listStr.add(line);
}
}
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return listStr;
}
}
I have a program that is supposed to load a text file and display/sort the data, however the data is not being displayed at all. Any ideas as to what I'm doing wrong? I have to stick with 1.4.2 Java only.
Here is the code:
import java.io.*;
import java.util.StringTokenizer;
class NewClass {
private static int quantity;
private static String[] name;
public static void main(String args[]) throws Exception {
InputStreamReader kb = new InputStreamReader(System.in);
BufferedReader in;
in = new BufferedReader(kb);
String buffer;
char choice;
boolean fileread=false;
int[]number=new int[quantity];
String[]name=new String[quantity];
String sorttype="";
do
{ //Setup Menu
choice=menu(in);
if(choice=='E')
{
if(fileread)
System.out.println("Data already has been entered");
else
{
fileread=true;
getdata(number,name);
}
}
else if(choice=='D')
{
if(fileread)
display(number,name,in);
else
System.out.println("Must enter data before it is displayed");
}
else if(choice=='S')
{
if(fileread)
sorttype=sort(number,name,in);
else
System.out.println("Must enter data before it is sorted");
}
} while(choice!='X');
}
//Sort Data
public static void sortint(int[] number, String[] name)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(number[i]>number[j])
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void sortstring(String[] name, int[] number)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(name[i].compareToIgnoreCase(name[j])>0)
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void swap(int[] a,int i,int j)
{
int t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static void swap(String[] a,int i,int j)
{
String t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static String sort(int[] number, String[] name, BufferedReader kb)throws Exception
{
String buffer;
do
{
//Allow user to sort the phone book
System.out.println("What do you want to sort by?");
System.out.println("Number");
System.out.println("Name");
System.out.print("Enter>>");
buffer=kb.readLine();
if(buffer.equalsIgnoreCase("number"))
{
sortint(number,name);
print(name, number,kb);
return buffer;
}
else if(buffer.equalsIgnoreCase("name"))
{
sortstring(name,number);
print(name,number,kb);
return buffer;
}
System.out.println("Invalid entry");
} while(true);
}
public static void print(String[] name, int[] number, BufferedReader kb)throws Exception
{
System.out.println("Sorted data");
System.out.println("Number\tName");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+"\t"+name[i]);
}
public static void display(int[] number, String[] name, BufferedReader kb)throws Exception
{
System.out.println("Number Name");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+" "+name[i]);
}
public static void getdata(int number[],String name[])throws Exception
{
FileReader file = new FileReader("phoneData.txt");
try (BufferedReader input = new BufferedReader(file)) {
int i;
String buffer;
for( i=0;i<quantity;i++)
{
buffer=input.readLine();
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
}
}
}
public static char menu(BufferedReader kb)throws Exception
{
String buffer;
char input;
do
{
System.out.println("\nWhat would you like to do?");
System.out.println("E-Enter phone book data");
System.out.println("D-Display phone book data");
System.out.println("X-Exit program");
System.out.println("S-Sort list");
System.out.print("Enter E, D, X, S>>");
buffer=kb.readLine();
input=(buffer.toUpperCase()).charAt(0);
if(input=='E'||input=='D'||input=='X'||input=='S')
return input;
System.out.println("Invalid entry");
} while(true);
}
}
And here is what it is returning:
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>D
Number Name
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>
Any help is much appreciated.
You might want to initialize quantity
private static int quantity = 1;
instead of just
private static int quantity;
so that the code inside the the loop
for( i=0;i<quantity;i++)
can get a chance....
And as stated in my first comment, you should add some Exception handling and return value checking to your code.
Also you might just delete this line
private static String[] name;
since you have name declared locally in main.
EDIT
public static void getdata(int number[],String name[])throws Exception
{
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
int i;
String buffer;
for( i=0;i<quantity;i++)
{
// readLinde returns null when EOF is reached
buffer=input.readLine();
if(buffer != null) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
} else {
break; // since nothing left to read
// remaining buckets in the arrays are left empty
}
}
} catch (Exception e) {
// catch exceptions to where know your program fails
System.out.println(e.toString());
} finally {
if(input != null) {
// close the input stream when you are done
input.close();
}
}
}
Also you should consider using List instead of arrays
public static void getdata(List number,List name) {
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
String buffer;
while(null != (buffer = input.readLine())) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name.add(st.nextToken());
number.add(Integer.valueOf(Integer.parseInt((st.nextToken()).trim())));
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if(input != null) {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
}
}
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.
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>();