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
}
}
}
}
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(){}
}
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
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
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
}
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.