Adding two arrays to two columns in JavaFX TableView - java

I have successfully added one array to one column in TableView with the following code:
data = FXCollections.observableArrayList();
String[] a = {"a", "b"};
yearColumn.setCellValueFactory(new PropertyValueFactory<test3, String>("Year"));
interestColumn.setCellValueFactory(new PropertyValueFactory<test3, String>("Interest"));
principalColumn.setCellValueFactory(new PropertyValueFactory<test3, String>("Principal"));
balanceColumn.setCellValueFactory(new PropertyValueFactory<test3, String>("Balance"));
paymentsAnnual.setItems(data);
for (String anA : a) {
test3 test31 = new test3();
test31.year.setValue(anA);
data.add(test31);
}
test3.java
import javafx.beans.property.SimpleStringProperty;
public class test3 {
public SimpleStringProperty year = new SimpleStringProperty();
public SimpleStringProperty interest = new SimpleStringProperty();
public SimpleStringProperty principal = new SimpleStringProperty();
public SimpleStringProperty balance = new SimpleStringProperty();
public String getYear() {
return year.get();
}
public String getInterest() {
return interest.get();
}
public String getPrincipal() {
return principal.get();
}
public String getBalance() {
return balance.get();
}
}
Now I have a problem when I try to insert a new array to a different column at a time. say I have an array String[] b = {"hello", "hi"}, then I add it using the same for each loop, something like this
for (String anA : a) {
test3 test31 = new test3();
test31.year.setValue(anA);
data.add(test31);
}
for (String anA1 : b) {
test3 test31 = new test3();
test31.balance.setValue(anA1);
data.add(test31);
}
this adds the array but I get an output something like this
Can anyone tell me how to add them together?
UPDATE
How should I add array a and b together, which would give an output like this
UPDATE-2
I do have one way of doing it , by making it a double array
String[] a = {{"a", "b"},{"hello","hi"}};
for (int i = 1; i < a[0].length; i++){
test3 test31 = new test3();
test31.year.setValue(a[0][i]);
test31.balance.setValue(a[1][i]);
data.add(test31);
}
this way I am able to add the contents at a time in its correct row, what if its a single array?

Every item in a TableView's items list represents one row.
Your first loop adds two rows, which each have a year defined but have no other properties defined.
Your second loop adds two more rows, which each have a balance defined but have no other properties defined.
You must modify the existing objects in your List instead of adding more rows.

Related

How do I import a populated ready-made ArrayList from another class in java?

I'm working with a large set of imported data and retrieving certain parts of it in the main method with 2 classes(WeatherStation, WeatherReading).The data is temperature readings at loads of weather stations(station id, name, lat, lon, year, time, temp etc) I made a third class (SoloSiteIds) whose sole purpose was to return a whole and complete ArrayList of the site ids with no duplication. But I cannot import the ArrayList from the other class into my main method. My SoloSiteIds class looks like this:
public class SoloSiteIds {
static ArrayList <Integer> siteIds = new ArrayList <Integer>();
public SoloSiteIds() {
}
public SoloSiteIds( ArrayList <Integer> siteIds) {
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ",
String siteid = elements[0]; // convert all the site id's at index 0 to integers
int id = Integer.parseInt(siteid);
if(!siteIds.contains(id)) {
siteIds.add(id);
}
this.siteIds=siteIds;
}
}
}
public static ArrayList<Integer> getSiteIds() {
return siteIds;
}
public ArrayList<Integer> setSiteIds(ArrayList<Integer> siteIds) {
return this.siteIds = siteIds;
}
}
The main method where I am trying to import the ArrayList "siteIds" looks like this:
WeatherStation thisStation = new WeatherStation (id, name, lat, lon);
WeatherReading thisReading = new WeatherReading(year, month, date, hour, windSpeed, temp);
SoloSiteIds siteList= new SoloSiteIds();
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ","
String siteid = elements[0]; // convert all the site id's at index 0 to integers
id = Integer.parseInt(siteid);
thisStation.setId(id);
thisStation.setName(elements[1]);
//parse the different elements into different data types
String stringLat = elements[2];
lat= Double.parseDouble(stringLat);
lat = thisStation.setLat(lat);
lat=thisStation.setLat(lat);
String stringLon = elements[3];
lon= Double.parseDouble(stringLon);
lat = thisStation.setLon(lon);
lat=thisStation.setLon(lon);
String stringTemp=elements[9];
temp=Double.parseDouble(stringTemp);
temp=thisReading.setTemp(temp);
Only the top part is relevant. I have tried lots of different variation of .set and .get using "thisList" instance and a new ArrayList like
ArrayList<Integer> siteIds = thisList.setSiteIds();
ArrayList<Integer> siteIds= SoloSiteIds.getSiteIds();
thisList=Siteids.setSiteIds();
thisList=SingleSoloSites.setSiteIds();
etc etc. This might look stupid but im just showing Ive tried numerous things and i am stuck
Thanks
I believe your problem is that you are initializing siteIds as an empty Arry list but you are not setting the data in a static way (the set Method is not static).
As far as I am aware of your situation, I belive that the SoloSiteIds class is unnescessary. I would solve your problem with an ArrayList declared in your main class and initialize with a getSoleIds() method also declared in your main class.
The getSoleIds() Method should contain the code currently in the SoleSiteIds initializer.

Load 2D array variables into class intances

I'm lacking the knowledge on 2d arrays and I need help populating data from an array into a few class variables.
So I have simple product class that looks like this:
public class Product{
int prodID;
String prodName;
Double prodCost;
int prodQuantity;
I also have a class with two methods:
Taking a CSV and converting it to an array - done
Taking variables from the array and adding them to the appropriate variables - not finished
The array/CSV looks like this:
product ID | product name | product cost | quantity
-----001----- | -----item1----- | -----5.99----- | -----3-----
-----002----- | -----item2----- | -----2.99----- | -----5-----
I want to write code that iterates over the array, and creates Product instances for each line. Eventually I will have a list of products. I can always assume the CSV is in fixed format so there will always only be 4 variables as seen in the table above.
So this is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class productsImport extends Product {
public static List<List<String>> csvToArray() {
String fileName = "c:\\temp\\test.csv";
File file = new File(fileName);
// this gives you a 2-dimensional array of strings
List<List<String>> lines = new ArrayList<>();
Scanner inputStream;
try {
inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String line = inputStream.next();
String[] values = line.split(",");
// this adds the currently parsed line to the 2-dimensional string array
lines.add(Arrays.asList(values));
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return lines;
}
public static void mapToProdcut(List<List<String>> lines){
for (List<String> line : lines) {
Product p = new Product();
for (String value : line) {
???
}
}
}
public static void main(String[] args) {
csvToArray();
mapToProdcut(csvToArray());
}
}
The first method converts the CSV to an array. The second method is where I'm stuck. I don't know how to iterate properly over the array to make sure that p.prodID, p.prodName, p.prodCost and p.prodQuantity are all populated with the corresponding column. I want to skip over the first row, because it will always show the field titles and they're not relevant.
Any help with this would be great :)
First thing to do is to create a constructor that takes all variables as parameters to simplify the code
public Product(int prodID, String prodName, Double prodCost, int prodQuantity) {
this.prodID = prodID;
this.prodName = prodName;
this.prodCost = prodCost;
this.prodQuantity = prodQuantity;
}
If you are running Java 8 you can use streams
List<Product> products =
lines.stream()
.skip(1)
.map(s -> new Product(
Integer.valueOf(s.get(0)),
s.get(1),
Double.valueOf(s.get(2)), Integer.valueOf(s.get(3))
)).collect(Collectors.toList());
Otherwise you can use a for loop
List<Product> products = new ArrayList<>();
for (int i = 1; i < lines.size(); i++) {
List<String> s = lines.get(i);
Product product = new Product(
Integer.valueOf(s.get(0)),
s.get(1),
Double.valueOf(s.get(2)),
Integer.valueOf(s.get(3)));
products.add(product);
}

How do I return/implement the toString for the ArrayList? Also, just want to check that I've correctly created my objects?

import java.util.ArrayList;
import java.util.Date;
import javafx.scene.shape.Circle;
public class List2 {
public static void main(String[] args){
Loan newLoan = new Loan();
Date theDate = new java.util.Date();
Circle newCircle = new Circle();
String s = new String();
//last semicolon is also an error?
private ArrayList<Object> List = new ArrayList<Object>();
List.add(newLoan);
List.add(theDate);
List.add(newCircle);
List.add(s);
//**There's an error underlining all my . and ; when I add them to the List above?
public String toString() {
String results = "";
for (Object d : List) {
results += "," + d.toString();
}
}
}
//I'm pretty new to this stuff
You have a lot of error in your code :
First
Don't ever name your variables with Upper letter in beginning, java use camelCase
Second
Don't declare your variable with private public in your method.
private ArrayList<Object> List = new ArrayList<Object>();
Third
You can't declare a method inside another method you have to close the first when you finish:
public static void main(String args[]){//------Start
...
}//---End
public String toString(){//---Start
...
}//---End
Forth
When you want to call a method with paramettres you can pass them like this :
method(list);
Fifth
ArrayList already impliment toString so you don't need to create it again, you can use :
list.toString()
If you want to implement it again you can use :
public static void main(String[] args) {
King newLoan = new King();
Date theDate = new java.util.Date();
Circle newCircle = new Circle();
String s = new String();
ArrayList<Object> list = new ArrayList<Object>();
list.add(newLoan);
list.add(theDate);
list.add(newCircle);
list.add(s);
System.out.println(newLoan.toString(list));
}
public String toString(ArrayList<Object> list) {
String results = "";
for (Object d : list) {
results += "," + d.toString();
}
return results;
}
firt thing first...
your code is not compiling since you are breaking the sintax rules...
this here:
private ArrayList<Object> List = new ArrayList<Object>();
can not be declared private since you are INSIDE a method, that is just invalid,
since List is used in an static context it must be declare Static too, or create an Object of the class List2
on the other hand
toString method returns a string object, you need to return something then, like results object I can infer.

How do you initialize a default constructor for String Arrays?

I am trying to add a default constructor to my data type. Right below the default constructor is the problem,"ingredients = " " ; ". It gives me an error saying String cannot be converted to String[]. What do I put after the equals sign to make it compile?
import java.util.Arrays;
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
ingredients = "" ;
instructions = "" ;
}
public String[] getIngredients() {
return ingredients;
}
public void setIngredients(String[] inIngredients) {
ingredients = inIngredients;
}
public String[] getInstructions() {
return instructions;
}
public void setInstructions(String[] inInstructions) {
instructions = inInstructions;
}
public void displayAll() {
System.out.println("The ingredients are " + ingredients);
System.out.println("The instructions are " + instructions);
}
}
It doesn't make sense to assign a String ("") to String[] (an array of Strings).
You may want to do one of the following in your default constructor, depending on your requirements:
Do nothing. The arrays were already initialized when they were declared, even if they are full of null elements.
Assign the empty string "" to every element. You can use a for loop for that, or an array initializer.
Assign null to the arrays. You are presumably replacing the array references later by calling setIngredients and setInstructions.
You are initializing a String array reference to a single string value thats why the compiler is going nuts.
You can do this
class Recipes {
private String[] ingredients = null;
private String[] instructions = null;
public Recipes(){
ingredients = new String[5]{"","","","",""};
instructions = new String[5]{"","","","",""};
}
I've reduced the size of the array for brevity. You can also use a for loop to assign fill in empty strings in the array if the array size is too large.
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
for(int i=0;i<ingredients.length;i++)
{
ingredients[i]="";
instructions[i]="";
}
}

Adding values of repeated elements in ArrayList

I have an Arraylist of Records.
package com.demo.myproject;
public class Records
{
String countryName;
long numberOfDays;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getNumberOfDays() {
return numberOfDays;
}
public void setNumberOfDays(long numberOfDays) {
this.numberOfDays = numberOfDays;
}
Records(long days,String cName)
{
numberOfDays=days;
countryName=cName;
}
}
My Arraylist<Records> is containing the values
Singapore 12
Canada 3
United Sates 12
Singapore 21
I need to modify it such that my output is
Canada 3
Singapore 33
United States 12
Please help me with solution,approach.
You could store your Records in a Map, where the key would be the country.
When you receive a new Record, check if the country already is in the map, if it is, add the number of days, if not create it.
Map<String, Record> map = new HashMap<String, Record> ();
addRecord(map, someRecord);
private void addRecord(Map<String, Record> map, Record record) {
Record inMap = map.get(record.getCountryName());
if (inMap == null) {
inMap = record;
} else {
inMap.setNumberOfDays(inMap.getNumberOfDays() + record.getNumberOfDays());
}
map.put(record.getCountryName(), inMap);
}
Notes:
I have assumed that it is fine to modify the records - if not just create a new one using the sum of the days.
you can still get the collection of records by calling map.values(); and iterate over them
ArrayList is not very well suited for your use case. If you really need to stick to ArrayList, for evey new record, you would need to loop over the list, check if one of the records in the list has the same country as the new record, update that record if you find it, or add a new record if not.
public class RecordsMain {
static ArrayList<Records> al = new ArrayList<Records>();
static boolean flag = false;
public static void main(String[] args) {
Records rec1 = new Records(12,"Singapore");
Records rec2 = new Records(3,"Canada");
Records rec3 = new Records(12,"United States");
Records rec4 = new Records(21,"Singapore");
addToList(rec1);
addToList(rec2);
addToList(rec3);
addToList(rec4);
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i).getCountryName() + " :: " + al.get(i).getNumberOfDays());
}
}
public static void addToList(Records records) {
for (int i = 0; i < al.size(); i++) {
if(al.get(i).getCountryName().equals(records.getCountryName())) {
al.get(i).setNumberOfDays(al.get(i).getNumberOfDays()+records.getNumberOfDays());
flag=true;
}
}
if (flag == false)
al.add(records);
}
}
Note:
The function addToList adds records and while adding itself checks whether the CountryNames are duplicate, if they are it adds the No of days and does not marks any new entry to the ArrayList.
I was not sure if you were looking for sorting of the List too, thus did not try that.
I suppose you create these records on your own. If you don't need any specific order of the elements you should use the HashMap and as assylias said - create country elements only when they doesn't exist. When you need to keep the order of elements (or sort them later by name etc) you can still use the ArrayList and "indexOf()" method to easily find them.
I dont know what exactly you want to do there but if you want to sort it with specific criteria then You could use comparable or comparator interfaces to sort your records using your criteria in ArrayList And use collections.sort() method to sort it.

Categories

Resources