Need help regarding duplicates records in JAVA - java

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

Related

Drop lines of code from a file

I'm working on a small project in which I need to remove some lines of commented code in java. There are two cases in which I should remove these lines: (i) when the line of code begins with //# and; (ii) when the line of code begins with //#.
However, the method I've developed for this case is not working on either type of removal:
private static void dropLines(String[] args, String f) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(f), Charset.forName("UTF-8"));
PrintWriter pw = new PrintWriter(new FileWriter(f));
boolean empty = false;
for (String string : lines) {
if (!string.trim().startsWith("//#")) {
if (string.trim().equals("") && !empty) {
pw.println(string);
empty = true;
} else if (!string.trim().equals("")) {
pw.println(string);
empty = false;
}
}
else if (!string.trim().startsWith("//#")) {
if (string.trim().equals("") && !empty) {
pw.println(string);
empty = true;
} else if (!string.trim().equals("")) {
pw.println(string);
empty = false;
}
}
}
pw.flush();
pw.close();
}
An example of an input file could be as follows:
public class Main {
//#ifdef calendar
//# public static void googleCalendar() {
//# System.out.println("Google Calendar");
//# }
//#endif
//#ifdef category
public static void addCategory() {
System.out.println("Add Category");
}
//#endif
public static void main(String[] args) {
//#ifdef base
//# System.out.println("Base");
//#endif
//#ifdef category
addCategory();
// #endif
//#ifdef calendar
//# googleCalendar();
//#endif
}
}
Important: although the input file has notations similar to preprocessing, this does not have any importance for this phase of removing the lines, because in theory, the preprocessing part is already done in previous methods with the use of Antenna. I need only create a method that deletes the rows after processing.
It looks like you'll want to change your surrounding if/else if statement to be a single if statement:
private static void dropLines(String[] args, String f) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(f), Charset.forName("UTF-8"));
PrintWriter pw = new PrintWriter(new FileWriter(f));
boolean empty = false;
for (String string : lines) {
if (!string.trim().startsWith("//#") && !string.trim().startsWith("//#")) {
if (string.trim().equals("") && !empty) {
pw.println(string);
empty = true;
} else if (!string.trim().equals("")) {
pw.println(string);
empty = false;
}
}
}
pw.flush();
pw.close();
}
With the way you have it right now, it's set up to always reprint the line, because if your line begins with "//#" then !string.trim().startsWith("//#") is true, and if it begins with "//#" then !string.trim().startsWith("//#") is true.

How to generate confusion matrix in c45?

I am trying to implement c45 algorithm on Map Reduce and the code here generates only a rule set given some training data.
This class contains the main method.
public class DecisionTreec45 extends Configured implements Tool
{
public static MySplit currentsplit=new MySplit();
public static List <MySplit> splitted=new ArrayList<MySplit>();
public static int current_index=0;
public static void main(String[] args) throws Exception {
MyMapper mp=new MyMapper();
splitted.add(currentsplit);
int res=0;
// double bestGain=0;
// boolean stop=true;
// boolean outerStop=true;
int split_index=0;
double gainratio=0;
double best_gainratio=0;
double entropy=0;
String classLabel=null;
int total_attributes=mp.no_Attr;
total_attributes=4;
int split_size=splitted.size();
MyGainRatio gainObj;
MySplit newnode;
while(split_size>current_index)
{
currentsplit = (MySplit) splitted.get(current_index);
gainObj = new MyGainRatio();
res = ToolRunner.run(new Configuration(), new DecisionTreec45(), args);
System.out.println("Current NODE INDEX . ::"+current_index);
int j=0;
int temp_size;
gainObj.getcount();
entropy=gainObj.currNodeEntophy();
classLabel=gainObj.majorityLabel();
currentsplit.classLabel=classLabel;
if(entropy!=0.0 && currentsplit.attr_index.size()!=total_attributes)
{
System.out.println("");
System.out.println("Entropy NOTT zero SPLIT INDEX:: "+entropy);
best_gainratio=0;
for(j=0;j<total_attributes;j++) //Finding the gain of each attribute
{
if(currentsplit.attr_index.contains(j)) // Splitting all ready done with this attribute
{
// System.out.println("Splitting all ready done with index "+j);
}
else
{
gainratio=gainObj.gainratio(j,entropy);
if(gainratio>=best_gainratio)
{
split_index=j;
best_gainratio=gainratio;
}
}
}
String attr_values_split=gainObj.getvalues(split_index);
StringTokenizer attrs = new StringTokenizer(attr_values_split);
int number_splits=attrs.countTokens(); //number of splits possible with attribute selected
String red="";
// int tred=-1;
System.out.println(" INDEX :: "+split_index);
System.out.println(" SPLITTING VALUES "+attr_values_split);
for(int splitnumber=1;splitnumber<=number_splits;splitnumber++)
{
temp_size=currentsplit.attr_index.size();
newnode=new MySplit();
for(int y=0;y<temp_size;y++) // CLONING OBJECT CURRENT NODE
{
newnode.attr_index.add(currentsplit.attr_index.get(y));
newnode.attr_value.add(currentsplit.attr_value.get(y));
}
red=attrs.nextToken();
newnode.attr_index.add(split_index);
newnode.attr_value.add(red);
splitted.add(newnode);
}
}
else
{
System.out.println("");
String rule="";
temp_size=currentsplit.attr_index.size();
for(int val=0;val<temp_size;val++)
{
rule=rule+" "+currentsplit.attr_index.get(val)+" "+currentsplit.attr_value.get(val);
}
rule=rule+" "+currentsplit.classLabel;
writeRuleToFile(rule);
if(entropy!=0.0)
System.out.println("Enter rule in file:: "+rule);
else
System.out.println("Enter rule in file Entropy zero :: "+rule);
}
split_size=splitted.size();
System.out.println("TOTAL NODES:: "+split_size);
current_index++;
}
System.out.println("COMPLETE");
System.exit(res);
}
public static void writeRuleToFile(String text)
{
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/hduser/C45/rule.txt/"), true));
bw.write(text);
bw.newLine();
bw.close();
} catch (Exception e) {
}
}
public int run(String[] args) throws Exception
{
JobConf conf = new JobConf(getConf(),DecisionTreec45.class);
conf.setJobName("c4.5");
// the keys are words (strings)
conf.setOutputKeyClass(Text.class);
// the values are counts (ints)
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(MyMapper.class);
conf.setReducerClass(MyReducer.class);
//set your input file path below
FileInputFormat.setInputPaths(conf, "/home/hduser/Id3_hds/playtennis.txt");
FileOutputFormat.setOutputPath(conf, new Path("/home/hduser/Id3_hds/1/output"+current_index));
JobClient.runJob(conf);
return 0;
}
}
This class is used to calculate the gain ratio.
public class MyGainRatio
{
int linenumber=0;
static String count[][]=new String[10000][4];
int currnode[]=new int[100];
String majorityLabel=null;
public String majorityLabel()
{
return majorityLabel;
}
//Calculation of entrophy
public double currNodeEntophy()
{
int currentindex=0;
double entropy=0;
currentindex=Integer.parseInt(count[0][0]);
int i=0;
int covered[]=new int[1000];
String classLabel=count[0][2];
int j=0;
int ind=-1;
int maxStrength=0;
System.out.println("Values in node rep to classwise");
while(currentindex==Integer.parseInt(count[j][0]))
{
if(covered[j]==0)
{
classLabel=count[j][2];
ind++;
i=j;
while(currentindex==Integer.parseInt(count[i][0]))
{
if(covered[i]==0)
{
if(classLabel.contentEquals(count[i][2]))
{
currnode[ind] = currnode[ind]+Integer.parseInt(count[i][3]);
covered[i]=1;
}
}
i++;
if(i==linenumber)
break;
}
if(currnode[ind]>maxStrength)
{
maxStrength=currnode[ind];
majorityLabel=classLabel;
}
System.out.print(" "+classLabel+" "+currnode[ind]);
}
else
{
j++;
}
if(j==linenumber)
break;
}
entropy=entropy(currnode);
return entropy;
}
public double entropy(int c[])
{
double entropy=0;
int i=0;
int sum=0;
double frac;
while(c[i]!=0)
{
sum=sum+c[i];
i++;
}
i=0;
while(c[i]!=0)
{
frac=(double)c[i]/sum;
entropy=entropy-frac*(Math.log(frac)/Math.log(2));
i++;
}
return entropy;
}
public void getcount()
{
DecisionTreec45 id=new DecisionTreec45();
FileInputStream fstream;
try {
fstream = new FileInputStream("/home/hduser/C45/output/intermediate" + id.current_index + ".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
//Read File Line By Line
StringTokenizer itr;
// System.out.println("READING FROM intermediate "+id.current_index);
while ((line = br.readLine()) != null) {
itr= new StringTokenizer(line);
count[linenumber][0]=itr.nextToken();
count[linenumber][1]=itr.nextToken();
count[linenumber][2]=itr.nextToken();
count[linenumber][3]=itr.nextToken();
int i=linenumber;
linenumber++;
}
count[linenumber][0]=null;
count[linenumber][1]=null;
count[linenumber][2]=null;
count[linenumber][3]=null;
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Close the input stream
}
}
public double gainratio(int index,double enp)
{
//100 is considered as max ClassLabels
int c[][]=new int[1000][100];
int sum[]=new int[1000]; //
String currentatrrval="#3#441get";
double gainratio=0;
int j=0;
int m=-1; //index for split number
int lines=linenumber;
int totalsum=0;
for(int i=0;i<lines;i++)
{
if(Integer.parseInt(count[i][0])==index)
{
if(count[i][1].contentEquals(currentatrrval))
{
j++;
c[m][j]=Integer.parseInt(count[i][3]);
sum[m]=sum[m]+c[m][j];
}
else
{
j=0;
m++;
currentatrrval=count[i][1];
c[m][j]=Integer.parseInt(count[i][3]); //(different class) data sets count per m index split
sum[m]=c[m][j];
}
}
}
int p=0;
while(sum[p]!=0)
{
totalsum=totalsum+sum[p]; //calculating total instance in node
p++;
}
double wtenp=0;
double splitenp=0;
double part=0;
for(int splitnum=0;splitnum<=m;splitnum++)
{
part=(double)sum[splitnum]/totalsum;
wtenp=wtenp+part*entropy(c[splitnum]);
}
splitenp=entropy(sum);
gainratio=(enp-wtenp)/(splitenp);
return gainratio;
}
public String getvalues(int n)
{ int flag=0;
String values="";
String temp="%%%%%!!#";
for(int z=0;z<1000;z++)
{
if(count[z][0]!=null)
{
if(n==Integer.parseInt(count[z][0]))
{
flag=1;
if(count[z][1].contentEquals(temp))
{
// System.out.println("Equals COUNT Index z "+z+" "+count[z][1]+ "temp "+temp);
}
else
{
values=values+" "+count[z][1];
temp=count[z][1];
}
}
else if(flag==1)
break;
}
else
break;
}
return values;
}
}
This mapper class checks whether this instance belongs to Current Node or not.
For all uncovered attributes it outputs index and its value
and class label of instance.
public class MyMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text attValue = new Text();
private Text cLabel = new Text();
private int i;
private String token;
public static int no_Attr;
//public static int splitAttr[];
private int flag=0;
public void map(LongWritable key, Text value,OutputCollector<Text, IntWritable> output,Reporter reporter) throws IOException {
DecisionTreec45 id=new DecisionTreec45();
MySplit split=null;
int size_split=0;
split=id.currentsplit;
String line = value.toString(); //changing input instance value to string
StringTokenizer itr = new StringTokenizer(line);
int index=0;
String attr_value=null;
no_Attr=itr.countTokens()-1;
String attr[]=new String[no_Attr];
boolean match=true;
for(i=0;i<no_Attr;i++)
{
attr[i]=itr.nextToken(); //Finding the values of different attributes
}
String classLabel=itr.nextToken();
size_split=split.attr_index.size();
for(int count=0;count<size_split;count++)
{
index=(Integer) split.attr_index.get(count);
attr_value=(String)split.attr_value.get(count);
if(attr[index].equals(attr_value)) //may also use attr[index][z][1].contentEquals(attr_value)
{
//System.out.println("EQUALS IN MAP nodes "+attr[index]+" inline "+attr_value);
}
else
{
// System.out.println("NOT EQUAL IN MAP nodes "+attr[index]+" inline "+attr_value);
match=false;
break;
}
}
//id.attr_count=new int[no_Attr];
if(match)
{
for(int l=0;l<no_Attr;l++)
{
if(split.attr_index.contains(l))
{
}
else
{
token=l+" "+attr[l]+" "+classLabel;
attValue.set(token);
output.collect(attValue, one);
}
}
if(size_split==no_Attr)
{
token=no_Attr+" "+"null"+" "+classLabel;
attValue.set(token);
output.collect(attValue, one);
}
}
}
}
This class counts number of occurrences of combination of ( index and
its value and class Label ) and prints count against it.
public class MyReducer extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
String line = key.toString();
// StringTokenizer itr = new StringTokenizer(line);
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
writeToFile(key + " " + sum);
/*
* int index=Integer.parseInt(itr.nextToken()); String
* value=itr.nextToken(); String classLabel=itr.nextToken(); int
* count=sum;
*/
}
public static void writeToFile(String text) {
try
{
DecisionTreec45 id = new DecisionTreec45();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
"/home/hduser/C45/output/intermediate" + id.current_index
+ ".txt"), true));
bw.write(text);
bw.newLine();
bw.close();
}
catch (Exception e)
{
}
}
}
This class Splits the attributes
public class MySplit implements Cloneable
{
public List attr_index;
public List attr_value;
double entophy;
String classLabel;
MySplit()
{
this.attr_index= new ArrayList<Integer>();
this.attr_value = new ArrayList<String>();
}
MySplit(List attr_index,List attr_value)
{
this.attr_index=attr_index;
this.attr_value=attr_value;
}
void add(MySplit obj)
{
this.add(obj);
}
}
The input training data set looks like this->
sunny hot high weak no
sunny hot high strong no
overcast hot high weak yes
rain mild high weak yes
rain cool normal weak yes
rain cool normal strong no
overcast cool normal strong yes
sunny mild high weak no
sunny cool normal weak yes
rain mild normal weak yes
sunny mild normal strong yes
overcast mild high strong yes
overcast hot normal weak yes
rain mild high strong no

How can i return an array in java that is accessible by other objects?

I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}

Using multiple classes getting Null pointer exception. Probably syntactical.

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>();

I can't figure out what's wrong, my logic seems correct

I know that what's messing up is my checkIfEdu method. Everything else is fine because I've tried it without that method. However, it's reading all the data into the InvalidStudentEmails file and its because of that method! i know it, everything else if fine because when I take that method out, it does everything correctly. Please help!!!
import java.util.Scanner;
public class CheckStudentEmail
{
public static void main (String[] args) throws Exception
{
java.io.File filein = new java.io.File("StudentEmailData.txt");
java.io.File fileout1 = new java.io.File("ValidStudentEmails.txt");
java.io.File fileout2 = new java.io.File("InvalidStudentEmails.txt");
Scanner input = new Scanner(filein);
java.io.PrintWriter validOutput = new java.io.PrintWriter(fileout1);
java.io.PrintWriter invalidOutput = new java.io.PrintWriter(fileout2);
writeHeadings(validOutput, invalidOutput);
StudentEmail student = new StudentEmail();
while (input.hasNext())
{
student.readStudentData(input);
if (student.checkPeriod() == true && student.checkAtSymbol() == true
&& student.checkIfEdu() == true)
student.writeEmails(validOutput);
else
student.writeEmails(invalidOutput);
}
input.close();
validOutput.close();
invalidOutput.close();
}
public static void writeHeadings(java.io.PrintWriter validOutput, java.io.PrintWriter invalidOutput)
{
validOutput.printf("%-20s%20s", "Name", "Email Address (Valid)"); validOutput.println(); validOutput.println();
invalidOutput.printf("%-20s%20s", "Name", "Email Address (Invalid)");
invalidOutput.println();
invalidOutput.println();
}
}
Here are my methods
import java.util.Scanner;
public class StudentEmail
{
private String stuName;
private String stuEmail;
StudentEmail()
{}
StudentEmail(String name, String email)
{
stuName = name;
stuEmail = email;
}
public void readStudentData(Scanner input)
{
stuName = input.next();
stuEmail = input.next();
}
public boolean checkPeriod()
{
if (stuEmail.indexOf(".") != -1)
return true;
else
return false;
}
public boolean checkAtSymbol()
{
int atSymbol;
if (stuEmail.indexOf('#') != -1)
{
atSymbol = stuEmail.indexOf('#');
if (stuEmail.indexOf('#', atSymbol+1) != -1)
return false;
else
return true;
}
else
return false;
}
public boolean checkIfEdu()
{
int lengthOfEmail = stuEmail.length();
int position = lengthOfEmail - 3;
String checkWord = stuEmail.substring(position);
if (checkWord == "edu")
return true;
else
return false;
}
public void writeEmails(java.io.PrintWriter output)
{
output.printf("%-20s%20s", stuName, stuEmail);
output.println();
}
}
you compare strings with the equals() method. Using '==' is comparing object references
Did you check what's the checkIfEdu() return?
Another thing is, as I have tried to run your checkIfEdu() it always return false. Because you are comparing it as reference.
To compare String, this should be like this:
if (checkWord.equals("edu")) {

Categories

Resources