Why are my text values returing -460? - java

This is a continuance of my previous post but on a different main topic. I don't know why my program reads the file and returns my error value of -460. There are 100 ints in my text file and 99 of them get returned as -460 and the last number in the file gets read correctly. I don't know what is going on! please help! Thank you!
import java.io.*;
import java.util.*;
public class projectFour
{
public static int [] global_numbers;
public static void main (String[] args)
{
read_file();
print_numbers(global_numbers);
}
public static void read_file()
{
try
{
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared? where is its value coming from?!?
{
try {
return Integer.parseInt(numbers);
} catch(NumberFormatException n) {
return -460;
}
}
public static void print_numbers(int [] numbers) // passing in an array called numbers but how does this array have values associated to it!?!
{
int max = numbers.length;
for(int i = 0; i < max; i++)
System.out.println(numbers[i]);
}
}

import java.io.*;
import java.util.*;
public class projectFour
{
public static int [] global_numbers;
public static void main (String[] args)
{
read_file();
print_numbers(global_numbers);
}
public static void read_file()
{
try
{
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine());
global_numbers = new int[amountOfNumbersInFile];
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers)
{
try {
return Integer.parseInt(numbers.trim());
} catch(NumberFormatException n) {
return -460;
}
}
public static void print_numbers(int [] numbers)
{
for(int i = 0; i < numbers.length; i++)
System.out.println(numbers[i]);
}
}

Related

FileNotFound Exception error in simple java filing code

I just started with this project and tried to check whether I was going the right way. I run this code but got one "FileNotFound exception must be caught or thrown" error. What do I do now? Am I going the right way?
package com.company;
import java.util.Scanner;
import java.io.File;
public class Main
{
public static void main(String[] args)
{
Game game = new Game();
String s = game.OpenFile();
System.out.println(s);
}
}
class Game
{
public Game(){
moviename = " ";
}
private String moviename;
public String OpenFile()
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Yes you are going in the right way. What this warning is saying is that you must handle the FileNotFound exception. You have two options: Throw it or surround the code in a try-catch block:
Throwing the exception:
public String OpenFile() throws FileNotFoundException
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Try-Catch:
public String OpenFile()
{
try {
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
}catch(Exception e) {
e.printStackTrace();
}
return moviename;
Some good readings:
Difference between try-catch and throw in java
https://beginnersbook.com/2013/04/try-catch-in-java/

Private constructor in class with static methods java

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

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
}

string arraylist delete an element and again put the element at the same position

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.

Categories

Resources