Why I can't show my list from another method? - java

Can you tell me why I can't see my list when I try to start it from another method? Below methods:
public class CollectionsOperation {
private List<Client> bufferedReaderClientLIst = new ArrayList<Client>();
private List<Client> emptyBoxForCf = new ArrayList<Client>();
BufferedReader bf = null;
private static final String fileName = "Clients.txt";
public List<Client> bufferedReaderCollection() throws IOException {
String line;
bf = new BufferedReader(new InputStreamReader (new FileInputStream(fileName), "UTF-8"));
while((line = bf.readLine()) != null) {
String[] split = line.split(";");
String nameCompany = split[0].substring(2);
String adress = split[1];
String phoneNumber = split[2];
String emailAdress = split[3];
Client k = new Client(nameCompany, adress, phoneNumber, emailAdress);
bufferedReaderClientLIst.add(k);
}
System.out.println(bufferedReaderClientLIst);
return bufferedReaderClientLIst;
}
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
Calling the method:
public static void main(String[] args) throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.show();
}
And this is the result what I get:
[ MarkCompany';Ilusiana';0982882902';mark#company.com, CorporationX';Berlin';93983';X#Corporation.com]
[]
Why the second list is empty ? the method bufferedReaderCollection() returns a result and the list bufferedReaderClientLIst is available to all methods. What is wrong?

In show():
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
You create another CollectionsOperation object to call bufferedReaderCollection() on. This is unnecessary.
However the problem is in the last print statement where you print bufferedReaderClientList. This is printing the bufferedReaderClientList of the this instance, not k. Because you have not called bufferedReaderCollection on this, the list will be empty, hence the [] printed at the end.
Instead of creating another instance, use this:
public void show() throws IOException {
this.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}

Related

Returning an arraylist to be accessed from another class

I'm new to Stackoverflow, so here goes.
I'm currently working on an assignment that requires to read from a csv file and place it into some sort of data collection.
I've gone with an arraylist. But what I seem to be stuck with is that I'm attempting to use my ReadWriteFile class to read the csv file into an arraylist (which works). But I need to somehow access that array in my GUI class to fill my JTable with said data.
After looking through similar help requests, I haven't been able to find any success.
My current code from my ReadWriteFile class;
public static void Read() throws IOException {
String lines = "";
String unparsedFile = "";
String dataArray[];
String col[] = { "COUNTRY", "MILITARY", "CIVILIAN", "POWER" };
FileReader fr = new FileReader("C:/Users/Corbin/Desktop/IN610 - Assignment 1/Programming3_WWII_Deaths.csv");
BufferedReader br = new BufferedReader(fr);
while ((lines = br.readLine()) != null) {
unparsedFile = unparsedFile + lines;
}
br.close();
dataArray = unparsedFile.split(",");
for (String item : dataArray) {
System.out.println(item);
}
ArrayList<String> myArrayList = new ArrayList<String>();
for (int i = 0; i < dataArray.length; i++) {
myArrayList.add(dataArray[i]);
}
}
So what my question is; How can I create a method that returns the values from the array, so I can access that array in my GUI class and add each element to my JTable?
Thanks!
Here is some simple example of how to return array in the method and how to use it in GUI class:
public class Main {
public String[] readFromFile (String filePath) {
ArrayList<String> yourList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
// read file content to yourList
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return yourList.toArray(new String[yourList.size()]);
}
}
And the GUI class:
public class GUI extends JFrame {
private JTable jTable;
public GUI() {
jTable = new JTable(10, 10);
this.getContentPane().add(jTable);
this.setVisible(true);
this.pack();
}
public void passArrayToTable(Main mainClass) {
String[] array = mainClass.readFromFile("C:\\file.csv");
// for (String s : array) {
// add values to jTable with: jTable.setValueAt(s,row,column);
// }
}
public static void main(String[] args) {
new GUI().passArrayToTable(new Main());
}
}

How to sort from text file and write into another text file Java

I have this textfile which I like to sort based on HC from the pair HC and P3
This is my file to be sorted (avgGen.txt):
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
6805.62,HC
17933.10,P3
Then my desired output into a new textfile (output.txt) is:
6805.62,HC
17933.10,P3
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
How can I sort the pairs HC and P3 from textfile where HC always appear for odd numbered index and P3 appear for even numbered index but I want the sorting to be ascending based on the HC value?
This is my code:
public class SortTest {
public static void main (String[] args) throws IOException{
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}
Collections.sort(rows);
for (Double toStr : rows){
convertString.add(String.valueOf(toStr));
}
FileWriter writer = new FileWriter("output.txt");
for(String cur: convertString)
writer.write(cur +"\n");
reader.close();
writer.close();
}
}
Please help.
When you read from the input file, you essentially discarded the string values. You need to retain those string values and associate them with their corresponding double values for your purpose.
You can
wrap the double value and the string value into a class,
create the list using that class instead of the double value alone
Then sort the list based on the double value of the class using either a Comparator or make the class implement Comparable interface.
Print out both the double value and its associated string value, which are encapsulated within a class
Below is an example:
static class Item {
String str;
Double value;
public Item(String str, Double value) {
this.str = str;
this.value = value;
}
}
public static void main (String[] args) throws IOException {
ArrayList<Item> rows = new ArrayList<Item>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(new Item(data[1], avg));
}
Collections.sort(rows, new Comparator<Item>() {
public int compare(Item o1, Item o2) {
if (o1.value < o2.value) {
return -1;
} else if (o1.value > o2.value) {
return 1;
}
return 0;
}
});
FileWriter writer = new FileWriter("output.txt");
for(Item cur: rows)
writer.write(cur.value + "," + cur.str + "\n");
reader.close();
writer.close();
}
When your program reads lines from the input file, it splits each line, stores the double portion, and discards the rest. This is because only data[0] is used, while data[1] is not part of any expression.
There are several ways of fixing this. One is to create an array of objects that have the double value and the whole string:
class StringWithSortKey {
public final double key;
public final String str;
public StringWithSortKey(String s) {
String[] data = s.split(",");
key = Double.parseDouble(data[0]);
str = s;
}
}
Create a list of objects of this class, sort them using a custom comparator or by implementing Comparable<StringWithSortKey> interface, and write out str members of sorted objects into the output file.
Define a Pojo or bean representing an well defined/organized/structured data type in the file:
class Pojo implements Comparable<Pojo> {
private double value;
private String name;
#Override
public String toString() {
return "Pojo [value=" + value + ", name=" + name + "]";
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* #param value
* #param name
*/
public Pojo(double value, String name) {
this.value = value;
this.name = name;
}
#Override
public int compareTo(Pojo o) {
return ((Double) this.value).compareTo(o.value);
}
}
then after that: read->sort->store:
public static void main(String[] args) throws IOException {
List<Pojo> pojoList = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader("chat.txt"));
String s;
String[] data;
while ((s = reader.readLine()) != null) {
data = s.split(",");
pojoList.add(new Pojo(Double.parseDouble(data[0]), data[1]));
}
Collections.sort(pojoList);
FileWriter writer = new FileWriter("output.txt");
for (Pojo cur : pojoList)
writer.write(cur.toString() + "\n");
reader.close();
writer.close();
}
Using java-8, there is an easy way of performing this.
public static void main(String[] args) throws IOException {
List<String> lines =
Files.lines(Paths.get("D:\\avgGen.txt"))
.sorted((a, b) -> Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.')))))
.collect(Collectors.toList());
Files.write(Paths.get("D:\\newFile.txt"), lines);
}
Even better, using a Method reference
public static void main(String[] args) throws IOException {
Files.write(Paths.get("D:\\newFile.txt"),
Files.lines(Paths.get("D:\\avgGen.txt"))
.sorted(Test::compareTheStrings)
.collect(Collectors.toList()));
}
public static int compareTheStrings(String a, String b) {
return Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.'))));
}
By using double loop sort the items
then just comapre it using the loop and right in the sorted order
public static void main(String[] args) throws IOException {
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:/Temp/AvgGen.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s;
try {
while((s = reader.readLine())!=null){
String[] data = s.split(",");
convertString.add(s);
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileWriter writer = new FileWriter("C:/Temp/output.txt");;
Collections.sort(rows);
for (double sorted : rows) {
for (String value : convertString) {
if(Double.parseDouble(value.split(",")[0])==sorted)
{
writer.write(value +"\n");
}
}
}

Output issues: Passing from BufferedReader to array method

I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")

Method is not working with reflection

One of my methods is not working which I used with both map and java reflection. I am not sure is it because of reflection or any other reason but it is working in other class where I didn't use reflection.
The method findAccessors() should retrieve a value from map2. The method is defined in the class ReadEdges. This method is called by another method findmethod() which is defined in the class FindMethod.
Whenever I call the method findAccessors() by the method findmethod(), it is returning an empty Linked List instead of returning the value from map2. The classes are given below:
Class ReadEdges :
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
public class ReadEdges {
static DFSclass dfs = new DFSclass();
List<String> sourcenodes=new ArrayList<String>(); // source node
List<String> destinationnodes=new ArrayList<String>(); // destination node
LinkedHashSet<String> findtransitions=new LinkedHashSet<String>();
LoanApprovalSystem LS = new LoanApprovalSystem();
TestdataGeneration testdata = new TestdataGeneration();
private static final String edgePat = "([a-zA-Z]|[0-9])+(,|\\x20)([a-zA-Z]|[0-9])+";
private static final String start=dfs.getstart();
private static final String edge = dfs.getedge();
private static final String transitions=dfs.gettransitions();
public static String a;
public static String b;
public static String c;
public static String d;
private Map<String, LinkedHashSet<String>> map = new HashMap();
private Map<String, LinkedHashSet<String>> map2 = new HashMap();
public int getLineCount(String edge){
int count = edge.split("[\n|\r]").length;
//System.out.println(count);
return count;
}
public void addEdge(String node1, String node2) throws IOException{
LinkedHashSet<String> adjacent = map.get(node1);
{
if(adjacent==null) {
adjacent = new LinkedHashSet();
map.put(node1, adjacent);
}
adjacent.add(node2);
}
}
public void addedgeandAccessor(String edge, String accessor) throws IOException{
LinkedHashSet<String> adjacent2 = map2.get(edge);
{
if(adjacent2==null) {
adjacent2 = new LinkedHashSet();
map2.put(edge, adjacent2);
//System.out.println(map2);
}
adjacent2.add(accessor);
//System.out.println(map2);
}
}
public void ReadEdge(String edgeinput,String transitionsinput,String accessorinput) throws InvalidInputException
{
char[] buf = edgeinput.toCharArray();
BufferedReader br = new BufferedReader(new CharArrayReader(buf));
char[] buf2 = transitionsinput.toCharArray();
BufferedReader br2 = new BufferedReader(new CharArrayReader(buf2));
String str2 = null;
char[] buf3 = accessorinput.toCharArray();
BufferedReader br3 = new BufferedReader(new CharArrayReader(buf3));
String str3 = null;
try
{
//a string for a next edge
String str = null;
//a StringTokinizer
StringTokenizer newNodes = null;
//get edges and set edges for the graph
while((((str = br.readLine()) != null) && (str2 = br2.readLine()) != null) && ((str3 = br3.readLine()) != null))
{
c=str;
d=str2;
LinkedHashSet<String> adjacent = map.get(str);
if(adjacent==null) {
adjacent = new LinkedHashSet();
map.put(str, adjacent);
}
adjacent.add(str2);
addedgeandAccessor(str,str3);
//if the edge inputs are not in good format, throw the exception
if(!Pattern.matches(edgePat, str.trim()))
JOptionPane.showMessageDialog(null,"An invalid input '" + str + "' for an edge. Please read the notes above the forms. ");
//use a comma to separate tokens
newNodes = new StringTokenizer (str, ", ");
//get the value of source node of an edge
String src = newNodes.nextToken();
//create the source node and destination node
String srcNode = src;
String desNode = newNodes.nextToken();
a=srcNode;
b=desNode;
addEdge(srcNode, desNode);
//System.out.println(adjacent);
//findTransition(a,b);
//findAccessors(a,b);
}
//System.out.println(listoftransitions);
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "Something is Wrong!");
e.printStackTrace();
}
}
public LinkedList<String> adjacentNodes(String last) {
LinkedHashSet<String> adjacent = map.get(last);
if(adjacent==null) {
return new LinkedList();
}
return new LinkedList<String>(adjacent);
}
public LinkedList<String> findTransition(String node1, String node2) throws IOException{
LinkedHashSet<String> adjacent = map.get(node1+" "+node2);
if(adjacent==null) {
return new LinkedList();
}
findtransitions = adjacent;
return new LinkedList<String>(findtransitions);
}
public LinkedList<String> findAccessors(String node1, String node2) {
LinkedHashSet<String> adjacent = map2.get(node1+" "+node2);
if(adjacent==null) {
return new LinkedList();
}
System.out.println(adjacent);
return new LinkedList<String>(adjacent);
}
public String getsrcNode(){
return a;
}
public String getedgeline(){
return c;
}
public String gettransitionline(){
return d;
}
}
Class FindMethod :
import java.util.ArrayList;
import java.util.LinkedList;
import java.lang.reflect.*;
public class FindMethod {
ReadEdges r = new ReadEdges();
LoanApprovalSystem LS = new LoanApprovalSystem();
TestdataGeneration testdata = new TestdataGeneration();
int method1;
String method2;
boolean method3;
boolean method4;
String method5;
String m;
//returns the method name using refletion
public String getmethod(Method method){
FindMethod fm = new FindMethod();
m = method.getName();
String str = "";
str += m+"(" +fm.getparameter(method)+ ")";
// System.out.println(str);
return str;
}
//returns the parameter name of the method using refletion (i.e. (int))
public String getparameter(Method method){
String str = "";
Class<?>[] params = method.getParameterTypes();
for (int i = 0; i < params.length; i++) {
if (i > 0) {
str += ", ";
}
str += (params[i].getSimpleName());
}
return str;
}
public void findmethod(String s,String t,String transition) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
FindMethod fm = new FindMethod();
LoanApprovalSystem cls = new LoanApprovalSystem();
Class<? extends LoanApprovalSystem> c = cls.getClass();
Object obj = c.newInstance();
Method[] methods = LoanApprovalSystem.class.getMethods();
for(Method method : methods)
{
//returns the method name (i.e. Receive or Asses)
m = method.getName();
fm.getmethod(method);
if(transition.equals(fm.getmethod(method)) && (transition.equals("Receive(int)")) )
{
if(fm.getparameter(method).equals("int") )
{
//LS.Receive(testdata.TestData(s,t));
//invoking the method at runtime where m="Receive".
method = c.getMethod(m, int.class);
method.invoke(obj,testdata.TestData(s,t));
LinkedList<String> accessors= r.findAccessors(s,t);
System.out.println("A:"+accessors);
method1=LS.getamount();
System.out.println(m+"("+method1+")");
System.out.println("Amount: "+method1);
}
}
}
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
{
FindMethod fm = new FindMethod();
fm.findmethod("1","2","Receive(int)");
}
}
Can anybody please tell me why my method findAccessors() is not working within the method findmethod()? Or please give me a solution of this problem.
Note: There is another class used in this program LoanApprovalSystem (). If anyone need I can give the definition of that class too.
It looks like you are calling the default constructor for ReadEdges:
'ReadEdges r = new ReadEdges();'
When you need to call your constructor that populates the maps:
'ReadEdges r = new ReadEdges(edgeinput, transitionsinput, accessorinput);'
EDIT:
The function
public void ReadEdge(String edgeinput, String transitionsinput, String accessorinput); is never being called.
You need to remove void and add as 's' to ReadEdge to make it a constructor:
public ReadEdges(String edgeinput, String transitionsinput, String accessorinput);
Then, when you instantiate ReadEdges in the FindMethod class, you need to supply the arguments.
ReadEdges r = new ReadEdges();
should be:
ReadEdges r = new ReadEdges(edgeinput, transitionsinput, accessorinput);
For more information, read about 'constructor overloading' and 'method overloading'. http://beginnersbook.com/2013/05/constructor-overloading/

How to design a data driven JUnit test class

#Parameters
public static Collection data() throws IOException {
ArrayList<String> lines = new ArrayList();
URL url = PokerhandTestCase.class.getClassLoader().getResource("test/TestFile.txt");
File testFile = new File(url.getFile());
FileReader fileReader = new FileReader(testFile);
bufReader = new BufferedReader(fileReader);
assertFalse("Failed to load the test file.", testFile == null);
boolean isEOF = false;
while (!isEOF){
String aline = bufReader.readLine();
if (aline == null){
System.out.println("Done processing.");
isEOF = true;
}
lines.add(aline);
}
return Arrays.asList(lines);
}
The last line of the program is causing the crash, I would like to know what is the proper way to define a collection from a arrayList. This function is required to Collection as the return type.
Replace last line with this:
return (Collection)lines;
Since ArrayList implements Collection interface: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
So overall code:
public static Collection data() throws IOException
{
ArrayList<String> lines = new ArrayList();
// populate lines collection...
return (Collection)lines;
}
Based on the comments below, perhaps this would qualify as "Collection of arrays":
public static Collection data() throws IOException
{
ArrayList<String> array1 = new ArrayList();
ArrayList<String> array2 = new ArrayList();
ArrayList<String> array3 = new ArrayList();
// populate lines collection...
ArrayList<ArrayList<String>> lines = new ArrayList();
lines.add(array1);
lines.add(array2);
lines.add(array3);
return (Collection)lines;
}
ArrayList lines = new ArrayList();
...
return Arrays.asList(lines);
this return two-dimensional array.
This function is required to Collection as the return type.
I think user1697575's answer is correct.
Your collection that you are returning needs to be a Collection<Object[]>. You are returning a Collection. You need to do something like this (for a complete example):
#RunWith(Parameterized.class)
public class MyTest {
#Parameters
public static Collection<Object[]> data() throws IOException {
List<Object[]> lines = new ArrayList<>();
File testFile = new File("/temp/TestFile.txt");
FileReader fileReader = new FileReader(testFile);
BufferedReader bufReader = new BufferedReader(fileReader);
Assert.assertFalse("Failed to load the test file.", testFile == null);
boolean isEOF = false;
while (!isEOF) {
String aline = bufReader.readLine();
if (aline == null) {
System.out.println("Done processing.");
isEOF = true;
}
lines.add(new Object[] { aline });
}
return lines;
}
private final String file;
public MyTest(String file) {
this.file = file;
}
#Test
public void test() {
System.out.println("file=" + file);
}
}
Note that you're not closing the files here, and you're adding a useless null value to the end of the list, but I copied your code :-).

Categories