How to calculate the cumulative balance per customer account with a JTable? - java

I have a JTable in which I have the operations of several customer accounts.
I want to calculate the cumulative balance with each operation and this for each account. In my JTable I have a column (of type string) in which there is a list of accounts, another column (of type int) in which there is the amount of operations.
How will I be able to retrieve the list of accounts and calculate the cumulative balance of transactions for each account?

I have a solution of my problems
int nombreDeLignes = model.getRowCount();
double cumul=0;
String numcompte=null; // une valeur qui n'existe nulle part
for(int i=0; i<nombreDeLignes; i++) {
String numcompteLigne = model.getValueAt(i, 4).toString();
if ( numcompte==null || !numcompte.equals(numcompteLigne) ) {
numcompte = numcompteLigne;
cumul=0;
}
cumul+= (int) model.getValueAt(i, 5);
model.setValueAt(cumul, i, 9);
}

Here is a code to create Consolidate the Data and create SubTotal
public enum AggregatorType {
SUM, AVG, DISPLAY, LABEL
}
public class DataRow {
private final Object[] values;
private final boolean totalRow;
public DataRow(Object[] values, boolean totalRow) {
this.values = values;
this.totalRow = totalRow;
}
public Object[] getValues() {
return values;
}
public boolean isTotalRow() {
return totalRow;
}
public static Object[] getvalues(Object obj) {
if (obj instanceof DataRow) {
return ( (DataRow) obj).getValues() ;
} else if (obj instanceof Object[]) {
return (Object[]) obj;
} else {
return new Object[] { obj};
}
}
}
public class Aggregator {
private final int column;
private final String prefix;
private final String subfix;
private final AggregatorType type;
public Aggregator( int column,AggregatorType type)
{
this(column,type,null);
}
public Aggregator( int column,AggregatorType type,String prefix)
{
this(column,type,prefix,null);
}
public Aggregator( int column,AggregatorType type,String prefix,String subfix)
{
this.column=column;
this.type=type;
this.prefix=prefix;
this.subfix=subfix;
}
public int getColumn() {
return column;
}
public AggregatorType getType() {
return type;
}
public Object aggregate( List<?> objects) {
Object object = null;
switch(this.type) {
case SUM : object = total(objects); break;
case AVG : object = avg(objects); break;
case LABEL: object = ""; break;
default: object = display(objects); break;
}
if( object != null && ( prefix != null || subfix != null )) {
return ( prefix == null ? "" : prefix.toString() ) +
object.toString() +
( subfix == null ? "" : subfix.toString() );
} else {
return object;
}
}
public Object display( List<?> objects) {
return DataRow.getvalues(objects.get(0))[column];
}
public Object total( List<?> objects) {
double total = 0.0;
for( Object object : objects ) {
Object[] objA = DataRow.getvalues(object);
Object value = objA[column];
if( value instanceof Number ) {
total += ( ( Number ) value ).doubleValue();
}
}
return total;
}
public Object avg( List<?> objects) {
double total = 0.0;
int count = 0;
for( Object object : objects ) {
Object[] objA = DataRow.getvalues(object);
Object value = objA[column];
if( value instanceof Number ) {
total += ( ( Number ) value ).doubleValue();
count++;
}
}
return count > 0 ? ( total / count ) : 0.0;
}
}
import java.util.List;
public class SubTotalCreator {
private final int columnIndex;
private final boolean grandTotal;
private final List<Aggregator> aggregatorList;
public SubTotalCreator(int index, List<Aggregator> aggregatorList) {
this(index, false, aggregatorList);
}
public SubTotalCreator(int index, boolean grandTotal, List<Aggregator> aggregatorList) {
this.aggregatorList = aggregatorList;
this.columnIndex = index;
this.grandTotal = grandTotal;
}
public boolean canCreateSubTotal(Object[] object1, Object[] object2) {
return !object1[columnIndex].equals(object2[columnIndex]);
}
public Object[] createSubTotal(List<?> subList) {
Object[] obj = DataRow.getvalues(subList.get(0));
int length = obj.length;
Object[] subtotal = new Object[length];
for (Aggregator aggregator : aggregatorList) {
Object value = aggregator.aggregate(subList);
subtotal[aggregator.getColumn()] = value;
}
return subtotal;
}
public int getColumnIndex() {
return columnIndex;
}
public boolean isGrandTotal() {
return grandTotal;
}
public List<Aggregator> getAggregatorList() {
return aggregatorList;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Consolidator {
private final List<SubTotalCreator> list;
private final Comparator<Object[]> comparator;
private List<Object[]> objects;
private List<DataRow> rows;
public Consolidator(Comparator<Object[]> comparator, List<SubTotalCreator> list) {
this.comparator = comparator;
this.list = list;
}
public List<Object[]> getSummary() {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
if (row.isTotalRow()) {
list.add(row.getValues());
}
}
return list;
}
public Object[][] getAllRowAsArray() {
Object[][] list =new Object[rows.size()][];
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
list[index]=row.getValues();
}
return list;
}
public List<Object[]> getAllRows() {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
list.add(row.getValues());
}
return list;
}
public List<Object[]> getObjects() {
return objects;
}
public List<DataRow> getRows() {
return rows;
}
public void setObjects(Object[][] objects) {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < objects.length; index++) {
list.add(objects[index]);
}
setObjects(list);
}
public void setObjects(List<Object[]> objects) {
this.objects = objects;
}
private void createDataRow() {
List<DataRow> list = new ArrayList<>();
for (int index = 0; index < objects.size(); index++) {
list.add(new DataRow(objects.get(index), false));
}
this.rows = list;
}
public void consolidate() {
objects.sort(comparator);
createDataRow();
computeSubTotal();
computeGrandTotal();
}
public void computeSubTotal() {
for (SubTotalCreator creator : list) {
if (!creator.isGrandTotal()) {
computeSubTotal(creator);
}
}
}
public void computeGrandTotal() {
for (SubTotalCreator creator : list) {
if (creator.isGrandTotal()) {
computeSubTotal(creator);
}
}
}
public void computeSubTotal(SubTotalCreator creator) {
List<?> list = null;
if (!creator.isGrandTotal()) {
ArrayList<DataRow> subList = new ArrayList<DataRow>();
DataRow prevDataRow = null;
for (int index = 0; index < rows.size(); index++) {
DataRow dataRow = rows.get(index);
if (dataRow.isTotalRow())
continue;
if (prevDataRow != null) {
boolean flag = creator.canCreateSubTotal(prevDataRow.getValues(), dataRow.getValues());
if (flag) {
DataRow subTotal = new DataRow(creator.createSubTotal(subList), true);
rows.add(index, subTotal);
subList.clear();
index++;
}
}
subList.add(dataRow);
prevDataRow = dataRow;
}
list = subList;
} else {
list = objects;
}
DataRow subTotal = new DataRow(creator.createSubTotal(list), true);
rows.add(subTotal);
}
public static void print(Object[][] objects) {
for (Object[] objA : objects) {
System.out.println(Arrays.asList(objA));
}
}
public static void print(List<Object[]> objects) {
for (Object[] objA : objects) {
System.out.println(Arrays.asList(objA));
}
}
public static void main(String[] str) {
Object[][] accountDetails = new Object[][] { { "Abhi", 20 }, { "Abhi", 200 }, { "Sekar", 100 }, { "Abhi", 45 },
{ "Sekar", 120 }, { "Abhi", 35 }, { "Abhi", 40 }, { "Sekar", 500 } };
Comparator<Object[]> comparator = new Comparator<Object[]>() {
public int compare(Object[] obj1, Object[] obj2) {
return ((String) obj1[0]).compareTo((String) obj2[0]);
}
};
List<SubTotalCreator> list = new ArrayList<SubTotalCreator>();
List<Aggregator> aggregatorList = new ArrayList<Aggregator>();
aggregatorList.add(new Aggregator(0, AggregatorType.DISPLAY, null, " 's Total"));
aggregatorList.add(new Aggregator(1, AggregatorType.SUM));
SubTotalCreator creator = new SubTotalCreator(0, aggregatorList);
list.add(creator);
List<Aggregator> grandAggList = new ArrayList<Aggregator>();
grandAggList.add(new Aggregator(0, AggregatorType.LABEL, "Grand Total"));
grandAggList.add(new Aggregator(1, AggregatorType.SUM));
SubTotalCreator creator2 = new SubTotalCreator(0, true, grandAggList);
list.add(creator2);
Consolidator consolidator = new Consolidator(comparator, list);
consolidator.setObjects(accountDetails);
System.out.println("Before Consolidate ");
print(consolidator.getObjects());
consolidator.consolidate();
System.out.println("After Consolidate ");
print(consolidator.getAllRows());
System.out.println("After Consolidate Summary Alone ");
print(consolidator.getSummary());
JFrame frame = new JFrame("test");
JTable table = new JTable( consolidator.getAllRowAsArray(),new String[] {"Name" ,"Amount"});
frame.getContentPane().add( new JScrollPane(table),BorderLayout.CENTER);
frame.setSize( 400,400);
frame.setVisible( true);
}
}

Related

TreeTableView: Displaying different data types

I have a Factory class which contains a list of employees. I want to use a TreeTableView to display the Factory data. It is pretty forward to display the name and the size of a Factory, but i don't know how to display the employees names!
public class Factory {
private String name;
private double size;
private List<Employee> employees;
public Factory(name, size){this.name=name; this.size=size}
// Getters & setters
}
I want to have the following output:
With the possibilty to fold the factory.
In a TreeView or TreeTableView all nodes in the tree have to be of the same type. This makes the kind of design you want (which is very natural) something of a pain. Basically, you have to make the type of the TreeView or TreeTableView the most specific superclass of all the types of rows you want in the tree: i.e. in this case the type of the TreeTableView needs to be a superclass of both Employee and Factory. Then the cell value factories on the columns would have to type test the row objects to determine what value to return.
It would be unusual to have an object model in which these were related by inheritance other than both being subclasses of Object, so you probably need a TreeTableView<Object> here.
So roughly speaking (if you are using plain old JavaBean style, instead of the recommended JavaFX properties), you would define something like
TreeTableView<Object> treeTable = new TreeTableView<>();
treeTable.setShowRoot(false);
TreeTableColumn<Object, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleStringProperty(f.getName());
} else {
return new SimpleStringProperty("");
}
});
TreeTableColumn<Object, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleObjectProperty<Number>(Double.valueOf(f.getSize()));
} else {
return new SimpleObjectProperty<Number>(null);
}
});
TreeTableColumn<Object, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Employee)) {
Employee emp = (Employee) rowItem.getValue() ;
return new SimpleStringProperty(emp.getName());
} else {
return new SimpleStringProperty("");
}
});
treeTable.getColumns().addAll(nameColumn, sizeColumn, employeeColumn);
and of course you populate it with
// fully initialized list of factories, with employee lists initialized:
List<Factory> factories = ... ;
TreeItem<Object> root = new TreeItem<>(null);
for (Factory factory : factories) {
TreeItem<Object> factoryItem = new TreeItem<>(factory);
root.getChildren().add(factoryItem);
for (Employee emp : factory.getEmployees()) {
TreeItem<Object> employeeItem = new TreeItem<>(emp);
factoryItem.getChildren().add(employeeItem);
}
}
treeTable.setRoot(root);
Here's a simple SSCCE using this:
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;
public class TreeTableExample extends Application {
#Override
public void start(Stage primaryStage) {
TreeTableView<Object> treeTable = new TreeTableView<>();
treeTable.setShowRoot(false);
TreeTableColumn<Object, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleStringProperty(f.getName());
} else {
return new SimpleStringProperty("");
}
});
TreeTableColumn<Object, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleObjectProperty<Number>(Double.valueOf(f.getSize()));
} else {
return new SimpleObjectProperty<Number>(null);
}
});
TreeTableColumn<Object, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Employee)) {
Employee emp = (Employee) rowItem.getValue() ;
return new SimpleStringProperty(emp.getName());
} else {
return new SimpleStringProperty("");
}
});
treeTable.getColumns().addAll(nameColumn, sizeColumn, employeeColumn);
List<Factory> factories = createData();
TreeItem<Object> root = new TreeItem<>(null);
for (Factory factory : factories) {
TreeItem<Object> factoryItem = new TreeItem<>(factory);
root.getChildren().add(factoryItem);
for (Employee emp : factory.getEmployees()) {
TreeItem<Object> employeeItem = new TreeItem<>(emp);
factoryItem.getChildren().add(employeeItem);
}
}
treeTable.setRoot(root);
Scene scene = new Scene(treeTable, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
}
private List<Factory> createData() {
String[][] empNames = {
{"John", "Jane", "Mary"},
{"Susan", "Mike"},
{"Alex", "Francois", "Joanne"}
};
List<Factory> factories = new ArrayList<>();
for (String[] emps : empNames) {
int count = factories.size()+1 ;
Factory f = new Factory("Factory "+ count, count*10);
for (String empName : emps) {
f.getEmployees().add(new Employee(empName));
}
factories.add(f);
}
return factories ;
}
public static class Employee {
private String name ;
public Employee(String name) {
this.name = name ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Factory {
private String name ;
private double size ;
private List<Employee> employees ;
public Factory(String name, double size) {
this.name = name ;
this.size = size ;
this.employees = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public List<Employee> getEmployees() {
return employees;
}
}
public static void main(String[] args) {
launch(args);
}
}
Another approach, which I think is a bit artificial, is to create a class representing the row in the table view, and then to make Factory and Employee subclasses of it:
public abstract class EmploymentEntity {
public String getName() {
return null ;
}
public Double getSize() {
return null ;
}
public String getEmployeeName {
return null ;
}
}
then
public class Employee extends EmploymentEntity {
private String name ;
public Employee(String name) {
this.name = name ;
}
#Override
public String getEmployeeName() {
return name ;
}
public void setEmployeeName(String name) {
this.name = name ;
}
}
and
public class Factory extends EmploymentEntity {
private String name ;
private double size ;
private List<Employee> employees ;
public Factory(String name, double size) {
this.name = name ;
this.size = size ;
this.employees = new ArrayList<>();
}
#Override
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
#Override
public Double getSize() {
return size ;
}
public void setSize(double size) {
this.size = size ;
}
public List<Employee> getEmployees() {
return employees ;
}
}
This object model is really unnatural (to me, anyway), but it does make the table a little easier:
TreeTableView<EmploymentEntity> treeTable = new TreeTableView<>();
TreeTableColumn<EmploymentEntity, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValue().getName()));
TreeTableColumn<EmploymentEntity, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> new SimpleObjectProperty<Number>(cellData.getValue().getValue().getSize()));
TreeTableColumn<EmploymentEntity, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValue().getEmployeeName()));
// etc...

How to implement a Chain Comparator

I am creating the program that sorts an ArrayList of objects with parameters:
String name
int types(1-3)
int diffs(stands for difficulty, 1-3))
and in days(days until deadline).
I want to sort the list of objects using all parameters at sequentially in that order. I'm just getting used to comparators and was wondering how exactly I would implement a comparator chain in my code.
I know there are other methods of doing this such as using if else statements inside one comparator or using compareToBuilder but I'm not sure which is best yet or if there are any other alternative methods I should consider.
Code for main:
import java.io.*;
import java.util.*;
public class InputItem
{
public int row;
public static void main(String args[])
{
String again;
String names[] = new String[100];
int types[] = new int[100];
int diffs[] = new int[100];
int days[] = new int[100];
int row=0;
do{
System.out.println("Please input assignment name:");
Scanner newNames = new Scanner(System.in);
String name = newNames.nextLine();
names[row] =name;
System.out.println("Please input assignment type:");
Scanner typeI = new Scanner(System.in);
int type = typeI.nextInt();
types[row] = type;
System.out.println("Please input assignment difficulty:");
Scanner diffI = new Scanner(System.in);
int diff = diffI.nextInt();
diffs[row] = diff;
// input days...
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
Scanner input = new Scanner(System.in);
again = input.next();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Itemss> WORK = new ArrayList<Itemss>();
for(int count = 0; count<row; count++)
{
WORK.add(new Itemss(((types[count])), (names[count])));
}
Collections.sort(WORK, new COMP());
System.out.println("Sorted List Entries: ");
for(Itemss a: WORK)
{
System.out.println(a);
}
}
}
Code for Itemss class and comparator
import java.util.*;
class COMP implements Comparator<Itemss>
{
#Override //overides compareTo() method
public int compare(Itemss a1, Itemss a2)
{
if((a1).getType()< (a2).getType())
{
return 1;
}
else
{
return -1;
}
}
}
public class Itemss
{
private String name;
private int type;
//private int diff;
//private int days;
public Itemss(int t, String n)
{
name = n;
type = t;
//diff = df;
//days = da;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String toString()
{
return this.name + "-->Type:" + this.type ;
}
}
To follow is a basic approach. Your previous Comparator was strictly comparing greater than or less than. To chain, compare the next set of variables when current variables are equal. Here is an example:
class COMP implements Comparator<Items> {
#Override // overides compareTo() method
public int compare(Items a1, Items a2) {
if (a1.getType() < a2.getType()) {
return 1;
} else if (a1.getType() > a2.getType()) {
return -1;
} else if (a1.getDiff() < a2.getDiff()) {
return 1;
} else if (a1.getDiff() > a2.getDiff()) {
return -1;
} else if (a1.getDays() < a2.getDays()) {
return 1;
} else if (a1.getDays() > a2.getDays()) {
return -1;
}
return 0;
}
}
Which creates a sample output like:
-- AFTER SORT --
Items [name=Item 8, type=3, diff=3, days=5]
Items [name=Item 9, type=3, diff=2, days=4]
Items [name=Item 7, type=3, diff=1, days=3]
Items [name=Item 4, type=2, diff=3, days=10]
Items [name=Item 5, type=2, diff=2, days=6]
Items [name=Item 6, type=2, diff=1, days=12]
Items [name=Item 3, type=1, diff=2, days=11]
Items [name=Item 1, type=1, diff=2, days=10]
Items [name=Item 2, type=1, diff=1, days=9]
You should use something like this:
public void order(List<MyObject> myList) {
Comparator<MyObject> byName = new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getName() != null && o2.getName() != null) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
return -1;
}
};
Comparator<MyObject> byType = new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getType() != null && o2.getType() != null) {
return o1.getType().compareTo(o2.getType());
}
return -1;
}
};
Comparator<MyObject> byDiffs = new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getDiffs() != null && o2.getDiffs() != null) {
return o1.getDiffs().compareTo(o2.getDiffs());
}
return -1;
}
};
Comparator<MyObject> byDays = new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getDays() != null && o2.getDays() != null) {
return o1.getDays().compareTo(o2.getDays());
}
return -1;
}
};
ComparatorChain chain = new ComparatorChain();
chain.addComparator(byName);
chain.addComparator(byType);
chain.addComparator(byDiffs);
chain.addComparator(byDays);
Collections.sort(myList, chain);
}

How can I split a line and assign index number for a graph's links connection in java?

I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}

Printing an array of objects in Java

I'm making a phone book and filling it with entries. The entries consist of two Strings for surname and initial, and a telephone number. I'm using an array to store the entries. I'm trying to get the array to print out and I've put toString methods in each class. But when I print out i'm still getting "[LEntry;#8dc8569". I'm not sure what I'm doing wrong. Here's the code.
public class Entry {
String surname;
String initial;
int number;
public Entry(String surname, String initial, int number) {
this.surname = surname;
this.initial = initial;
this.number = number;
}
public String getSurname(){
return surname;
}
public String getInitial(){
return initial;
}
public int getNumber() {
return number;
}
void setNumber(int number){
this.number = number;
}
public String toString(){
return surname+ "\t" +initial+ "\t" +number;
}
}
public class ArrayDirectory {
int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
public void addEntry(String surname, String initial, int num) {
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
}
public void deleteEntry(String surname, String initial) {
int i = findEntryIndex(surname, initial);
directory[i] = null;
}
public void deleteEntry(int number) {
int i = findEntryIndex(number);
directory[i] = null;
}
public int findEntry(String surname, String initial) {
int i;
i = findEntryIndex(surname, initial);
return directory[i].getNumber();
}
public void editNum(String surname, String initial, int number) {
int i;
i = findEntryIndex(surname, initial);
directory[i].setNumber(number);
}
public void print() {
// TODO print array
System.out.println(directory);
}
private int findEntryIndex(String surname, String initial) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getSurname().equals(surname) && directory[i].getInitial().equals(initial))
{
break;
}
}
return i;
}
private int findEntryIndex(int number) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getNumber() == number)
{
break;
}
}
return i;
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
public String toString() {
for(int i = 0 ; i< DIRECTORY_SIZE ; i++){
System.out.println( directory[i] );
}
return null;
}
}
public class Test {
public static void main(String[] args) {
ArrayDirectory phoneBook = new ArrayDirectory();
phoneBook.addEntry("Bigger", "R", 2486);
phoneBook.addEntry("Smaller", "E", 0423);
phoneBook.addEntry("Ringer", "J", 6589);
phoneBook.addEntry("Looper", "T", 6723);
phoneBook.addEntry("Lennon", "B", 4893);
phoneBook.addEntry("Martin", "M", 2121);
phoneBook.print();
}
}
Use Arrays.toString();
Arrays.toString(directory);
when you just print directory, which is an instance of array of type Entry, it doesn't override the toString() method the way you are expecting
Also See
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?

Writing information from SQL database to list

I'm working on my homework and I can't complete one piece of my program ...
I have JTable class which makes table in my code ... i have to write method which takes information from sql database and writes it in list
method MUST look like:
public static List selectAnswers (int questionId) throws SQLException, IOException
following code is written by me:
public static List<AnswerRow> selectAnswers (int questionId) throws SQLException, IOException
{
Connection veza = connectToDatabase();
Properties query = new Properties();
AnswersTableModel atm = new AnswersTableModel();
String selectAnswers = query.getProperty("selectAnswers");
PreparedStatement preparedStatement = veza.prepareStatement(selectAnswers);
ResultSet rs = preparedStatement.executeQuery();
List<AnswerRow> lista = new ArrayList<AnswerRow>();
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
?????????????????????????????????????????????????
}
closeConnectionToDatabase(veza);
return lista;
}
????? field is missing and i dont know what to write there to write information answeText and isRight into AnswerRow class , into AnswerTableModel, into list ...
Code which makes JTable (and is given to me and cannot be changed by my teacher) is here:
package hr.tvz.java.deveti.model;
import java.util.List;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class AnswersTableModel extends AbstractTableModel {
private Object[][] answers;
private String[] columnNames;
public AnswersTableModel (String[] colNames){
super();
columnNames = colNames;
}
public AnswersTableModel() {
super();
this.columnNames = new String[AnswerRow.TABLE_COLUMNS];
this.columnNames[0] = "Odgovor";
this.columnNames[1] = "Točan/Netočan";
}
public java.lang.Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
public int getColumnCount() {
return AnswerRow.TABLE_COLUMNS;
}
public int getRowCount() {
if (answers != null)
return answers.length;
else
return 0;
}
public Object getValueAt(int row, int column) {
return answers[row][column];
}
public String getColumnName(int column){
return columnNames[column];
}
public void setValueAt (Object aValue, int rowIndex, int columnIndex){
answers[rowIndex][columnIndex] = aValue;
}
public boolean isCellEditable (int rowIndex, int columnIndex){
return true;
}
public void addNewRow(){
Object[] o = new Object[] {"", false};
if ((answers == null) || (answers.length == 0)) {
answers = new Object[][] {o};
}else{
Object[][] answersTemp = new Object[answers.length + 1][AnswerRow.TABLE_COLUMNS];
for (int i = 0; i < answers.length; i++)
answersTemp[i] = answers[i];
answersTemp[answersTemp.length - 1] = o;
answers = answersTemp;
}
}
public List<AnswerRow> getAnswerRows() {
List<AnswerRow> list = new ArrayList<>();
for (Object[] oRow : answers) {
AnswerRow row = new AnswerRow();
row.setAnswer((String) oRow[0]);
row.setRight((boolean) oRow[1]);
list.add(row);
}
return list;
}
public void setAnswerRows(List<AnswerRow> answerRows){
if (answerRows.size() == 0 ) {
this.answers = new Object[0][0];
return;
}
this.answers = new Object[answerRows.size()][AnswerRow.TABLE_COLUMNS];
for (int i = 0; i < answers.length; i++){
answers[i][0] = answerRows.get(i).getAnswer();
answers[i][1] = answerRows.get(i).isRight();
}
this.columnNames = new String[AnswerRow.TABLE_COLUMNS];
this.columnNames[0] = "Odgovor";
this.columnNames[1] = "Točno/Netočno";
}
public class AnswerRow {
public static final int TABLE_COLUMNS = 2;
private boolean isRight;
private String answer;
public AnswerRow(){
answer = "";
isRight = false;
}
public AnswerRow(String answer, boolean isRight){
this.answer = answer;
this.isRight = isRight;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer){
this.answer = answer;
}
public boolean isRight(){
return isRight;
}
public void setRight(boolean isRight){
this.isRight = isRight;
}
}
}
Please help me .. thanks !
List<AnswerRow> lista = new ArrayList<AnswerRow>();
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
//Create AnswerRow instance and set values to it and Add it to list.
AnswersTableModel .AnswerRow ansrow = atm.new AnswerRow();
ansrow.setAnswer(answerText);
ansrow.setRight(isRight);
//Add it to list.
lista.add(ansrow);
}
One thing I am not sure is why you have AnswersTableModel and what you do with that.
Use public AnswerRow(String answer, boolean isRight) constructor to create object
AnswerRow ar=null;
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
ar=new AnswerRow(answerText, isRight);
lista.add(ar);
}

Categories