Displaying a 2d array JAVAFX - java

I'm trying to add all the values from different arrays to one 2d array and display it as a table in JavaFX.
Here's my try in doing it.
private StackPane table(Stage stage) {
StackPane root = new StackPane();
String[][] staffArray = new String[365][365];
staffArray[0][0] = "No. ";
staffArray[0][1] = "Check in";
staffArray[0][2] = "Check out";
staffArray[0][3] = "Name";
staffArray[0][4] = "Surname";
System.out.println(String.valueOf(arrRoom1[0][0]));
for (int i = 0; i < arrRoom1.length; i++) {
for (int y = 1; y < arrRoom1.length; y++) {
if (arrRoom1[i] == null) {
break;
}
staffArray[y][0] = String.valueOf(y);
staffArray[y][1] = String.valueOf(arrRoom1[i][0]);
staffArray[y][2] = String.valueOf(arrRoom1[i][1]);
staffArray[y][3] = String.valueOf(names1[i]);
staffArray[y][4] = String.valueOf(surnames1[i]);
}
}
System.out.println(staffArray[1][1]);
ObservableList<String[]> data = FXCollections.observableArrayList();
data.addAll(Arrays.asList(staffArray));
data.remove(0);//remove titles from data
TableView<String[]> table = new TableView<>();
for (int i = 1; i < staffArray.length; i++) {
for (int y = 0; y < 5; y++) {
if ( staffArray[i][y] == null) {
break;
}
TableColumn tc = new TableColumn(staffArray[i][y]);
final int colNo = i;
tc.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
return new SimpleStringProperty((p.getValue()[colNo]));
}
});
tc.setPrefWidth(90);
table.getColumns().add(tc);
}
}
table.setItems(data);
root.getChildren().add(table);
return root;
}
However, every time I get null values in staffArray after the loop. Where might the mistake be in the nested loop?

Related

how to sort ArrayList by id and add to ArrayList ArrayList<ArrayList<DataPost>>

I have mList2 with values. There are values with the same id. How can I get a List or ArrayList in which objects with the same id are grouped and add it to ArrayList>?
List<ProfileActivity.DataPost> mList2 = list;
List<List<ProfileActivity.DataPost>> output = new ArrayList<List<ProfileActivity.DataPost>>();
List<ProfileActivity.DataPost> itemsAlreadyGrouped = new ArrayList<ProfileActivity.DataPost>();
for (int i = 0; i < mList2.size(); i++) {
List<ProfileActivity.DataPost> groupList = new ArrayList<ProfileActivity.DataPost>();
boolean groupCandidateFound = false;
if (!itemsAlreadyGrouped.contains(mList2.get(i))) {
for (int j = 0; j < mList2.size(); j++) {
if (mList2.get(i).getIds_post().equals(mList2.get(j).getIds_post())) {
groupList.add(mList2.get(i));
groupCandidateFound = true;
}
}
if (groupCandidateFound) {
itemsAlreadyGrouped.add(mList2.get(i));
}
}
if (groupList.size() > 0) {
output.add(groupList);
}
}
//Let's test the logic
for (List<ProfileActivity.DataPost> group : output) {
System.out.println(group);
Toast.makeText(context, group.toString(),Toast.LENGTH_SHORT ).show();
}
DataPost
data class DataPost(var text:String? = null, var photo:String? = null,
var type:String = "",
var ids_post:String = "", var position:String? = null)
Make your ProfileActivity.DataPost class implements Comparable<ProfileActivity.DataPost> interface, the implement the compareTo(ProfileActivity.DataPost o) method
#Override
public void compareTo(ProfileActivity.DataPost o){
return getIds_post().compareTo(o.getIds_post());
}
Then just invoke Collections.sort(list)

Codename one calendar UpdateButtonDayDate() issue

I am working on my project where I want to show when application starts then calendar display, which date contain events, for instance if the date contain events, then the day button contains * symbol and day, And if the date doesn't contain any event then it only displays a day.
I wrote following code, but it only displays * symbol when I am clicking on that button, So how can I manage this code that display * symbol on the date which only contain events when the application starts or that page gonna be loaded.
Following is my code:-
public class Customised extends Calendar{
ArrayList<String[]> data = new ArrayList<>();
int i,j,columns;
#Override
protected void updateButtonDayDate(Button dayButton,int currentMonth, int day) {
dayButton.setText(""+day);
dayButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//Check which date having how many number of events===============================================================
try{
ShowEvent.removeAll();
cur = db.executeQuery("SELECT Event, Description from CalendarData WHERE Date = ? ", dateLabel.getText());
columns = cur.getColumnCount();
if(columns > 0) {
boolean next = cur.next();
if(next) {
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
}
}
}catch(IOException e){
e.printStackTrace();
}
for(i = 0 ; i< data.size(); i++){
Log.p(data.get(i)[0]);
}
Label a = new Label(dateLabel.getText());
Label b = new Label(" "+i);
Container container1 = TableLayout.encloseIn(2, a,b);
container1.setUIID("container1");
ShowEvent.add(container1);
for( i = 0 ; i< data.size(); i++){
for(j = 0; j<columns; j++){
Log.p(data.get(i)[j]);
SpanLabel spanData = new SpanLabel(data.get(i)[j]);
spanData.setUIID("SpanLabel");
ShowEvent.add(spanData);
}
Label space = new Label("=======================");
ShowEvent.add(space);
Log.p("###################");
}
data.clear();
if(i>0){
if(Dialog.show("Choose action", "What you want to do?", "Add Events","View Events")){
calendar.show();
}
else{
ShowEvent.show();
}
}else{
Dialog.show("Add event","There is no event to display, Please add events first","OK","");
}
//============================================================================================================
}
});
}
#Override
protected void initComponent(){
ArrayList<String[]> data1 = new ArrayList<>();
int k;
Log.p("initComponent");
try{
cur = db.executeQuery("select Date from CalendarData");
columns = cur.getColumnCount();
if(columns > 0) {
boolean next = cur.next();
if(next) {
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data1.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data1.size()][];
data1.toArray(arr);
}
}
}catch(IOException e){
e.printStackTrace();
}
for(k = 0 ; k< data1.size(); k++){
Log.p(data1.get(k)[0]);
}
if(k>0){
//cal.setUIID("CalendarSelectedDay");
}
}
/*
#Override
protected boolean isInitialized(){
boolean result = false;
Log.p("isInitialised");
return result;
}*/
public Customised(){
}
#Override
protected Button createDay() {
Button day = new Button();
day.setAlignment(CENTER);
day.setUIID("CalendarDay1");
day.setEndsWith3Points(false);
day.setTickerEnabled(false);
return day;
}
}
And the expected result will be:-
That's because you placed the code inside the actionPerformed method which is only triggered upon Button pressed/released.
Move your code to the updateButtonDayDate scope

Get ranks to iterating ArrayList value

I have five values in an ArrayList like {50,25,50,30,10} . I want to set ranks in every value, So please tell me how I could do this. The output is like
50->1st rank
50->1st rank
30->2nd rank
20->3rd rank
10->4th rank
you should check this and this.
It is easy to do with lambda expression which is available from java 1.8.
Here is code i have got from above reference link
List<Player> players = new ArrayList<Player>() {{
add(new Player(1L, "a", 5));
add(new Player(2L, "b", 7));
add(new Player(3L, "c", 8));
add(new Player(4L, "d", 9));
add(new Player(5L, "e", 3));
add(new Player(6L, "f", 8));
}};
int[] score = {Integer.MIN_VALUE};
int[] no = {0};
int[] rank = {0};
List<Ranking> ranking = players.stream()
.sorted((a, b) -> b.getScores() - a.getScores())
.map(p -> {
++no[0];
if (score[0] != p.getScores()) rank[0] = no[0];
return new Ranking(rank[0], score[0] = p.getScores());
})
// .distinct() // if you want to remove duplicate rankings.
.collect(Collectors.toList());
System.out.println(ranking);
// result:
// rank=1, score=9
// rank=2, score=8
// rank=2, score=8
// rank=4, score=7
// rank=5, score=5
// rank=6, score=3
Please try this code.
package snakePack;
import java.util.ArrayList;
public class MainSnake {
public static void main(String[] args) {
Snake blackMambo = new Snake("blackMambo",2,0);
Snake rattle = new Snake("rattle",9,0);
Snake green = new Snake("green",6,0);
Snake cobra = new Snake("cobra",78,0);
Snake kingCobra = new Snake("kingCobra",5,0);
Snake whiteCobra = new Snake("whiteCobra",5,0);
Snake python = new Snake("python",5,0);
Snake yellow = new Snake("yellow",5,0);
Snake blackCobra = new Snake("blackCobra",1000,0);
Snake desertCobra = new Snake("desertCobra",5,0);
ArrayList<Snake> list = new ArrayList<Snake>();
list.add(blackMambo);list.add(rattle);list.add(green);list.add(cobra);list.add(kingCobra);
list.add(whiteCobra);list.add(python);list.add(yellow);list.add(blackCobra);list.add(desertCobra);
ArrayList<Integer> mongoosebigSnakes = new ArrayList<Integer>();
Integer tempHelperFrog = 0;
Integer rankMe = 0;
for (int grossHopper = 0; grossHopper < list.size(); grossHopper++) {
Integer strongSnake = 0;
for (int spider = 0; spider < list.size(); spider++) {
if (list.get(spider).getSnakePoisionRate() > strongSnake) {
boolean bool = false;
if (mongoosebigSnakes.size() != 0) {
for (int dragonFly = 0; dragonFly < mongoosebigSnakes.size(); dragonFly++) {
if (mongoosebigSnakes.get(dragonFly).intValue() == list.get(spider).getSnakePoisionRate().intValue()) {
bool = true;
}
}
if (bool != true) {
bool = false;
strongSnake = list.get(spider).getSnakePoisionRate();
}
} else {
if (tempHelperFrog != list.get(spider).getSnakePoisionRate()) {
strongSnake = list.get(spider).getSnakePoisionRate();
}
}
}
}
tempHelperFrog = strongSnake;
mongoosebigSnakes.add(strongSnake);
++rankMe;
for (int x = 0; x < list.size(); x++) {
if (strongSnake == list.get(x).getSnakePoisionRate()) {
list.get(x).setSnakeRank(rankMe);
}
}
}
System.out.println(" Hey guys get ready to see who has strong poison >>>");
Integer ratHelperCounter = 0;
for (Snake snake : list) {
System.out.println(++ratHelperCounter + " :" + snake.toString());
}
System.out.println("it's awesome" + " huge me !!!! ");
}
}
Bean class:
package snakePack;
public class Snake {
String snakeName;
Integer snakePoisionRate;
Integer snakeRank;
public Snake(String string, int i, int j) {
this.snakeName = "";
this.snakePoisionRate = i;
this.snakeRank = j;
}
public String getSnakeName() {
return snakeName;
}
public void setSnakeName(String snakeName) {
this.snakeName = snakeName;
}
public Integer getSnakePoisionRate() {
return snakePoisionRate;
}
public void setSnakePoisionRate(Integer snakePoisionRate) {
this.snakePoisionRate = snakePoisionRate;
}
public Integer getSnakeRank() {
return snakeRank;
}
public void setSnakeRank(Integer snakeRank) {
this.snakeRank = snakeRank;
}
#Override
public String toString() {
return "Snake [snakeName=" + snakeName + ", snakePoisionRate="
+ snakePoisionRate + ", snakeRank=" + snakeRank + "]";
}
}

null pointer exception, not going inside loop

The requirement is:If <bby:SaleTenderType> value is eCommerce , it reads the SalesOrderNum and calls the required function(appends other nodes to the root node). <bby:SaleTenderType> is not eCommerce, it should call other function.
The java code is as below:
//Added for giftCard
//error
Lineitems = retailChildren.item(j).getChildNodes();
for (int z1 = 0; z1 < Lineitems.getLength(); z1++) {
if (Lineitems.item(z1).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild1 = Lineitems.item(z1).getChildNodes();
for (int z2 = 0; z2 < returnChild1.getLength(); z2++) {
if (returnChild1.item(z2).getNodeName().equalsIgnoreCase("Tender")) {
NodeList tenderChild = Lineitems.item(z2).getChildNodes(); //Null pointer exception
for (int z3 = 0; z3 < tenderChild.getLength(); z3++) {
if (tenderChild.item(z3).getNodeName().equalsIgnoreCase("bby:SaleTenderType")) {
System.out.println("Inside");
String SaleTenderType = tenderChild.item(z3).getFirstChild().getNodeValue();
if (SaleTenderType.equalsIgnoreCase("eCommerce")) {
Lineitems = retailChildren.item(j).getChildNodes();
for (int i2 = 0; i2 < Lineitems.getLength(); i2++) {
if (Lineitems.item(i2).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild = Lineitems.item(i2).getChildNodes();
for (int k = 0; k < returnChild.getLength(); k++) {
if (returnChild.item(k).getNodeName().equalsIgnoreCase("c360:SalesOrder")) {
String POSLOGSalesOrderNo = returnChild.item(k).getFirstChild().getNodeValue();
SalesOrderNo = POSLOGSalesOrderNo.substring(2, 12);
String SalesOrderNum = POSLOGSalesOrderNo.substring(0, 2);
if (SalesOrderNum.equalsIgnoreCase("HD") || (SalesOrderNum.equalsIgnoreCase("SV")) || (SalesOrderNum.equalsIgnoreCase("CR")) || (SalesOrderNum.equalsIgnoreCase("CW"))) {
if (!prevSalesOrder.equals(SalesOrderNo)) {
IDocEl = outdoc.createElement("IDOC");
ORDERS05.appendChild(createIDocHeader_GC(POSLOGSalesOrderNo, outdoc, EMPST, IDocEl, StoreID, true, returnChild, TRANS));
prevSalesOrder = SalesOrderNo;
}
IDocEl.appendChild(createE1EDP01forReturnLineItem_GC(outdoc, returnChild, StoreID));
}
}
}
}
}
}
}
}
} else {
Lineitems = retailChildren.item(j).getChildNodes();
for (int i3 = 0; i3 < Lineitems.getLength(); i3++) {
if (Lineitems.item(i3).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild = Lineitems.item(i3).getChildNodes();
for (int k = 0; k < returnChild.getLength(); k++) {
if (returnChild.item(k).getNodeName().equalsIgnoreCase("c360:SalesOrder")) {
String POSLOGSalesOrderNo = returnChild.item(k).getFirstChild().getNodeValue();
SalesOrderNo = POSLOGSalesOrderNo.substring(2, 12);
String SalesOrderNum = POSLOGSalesOrderNo.substring(0, 2);
if (SalesOrderNum.equalsIgnoreCase("HD") || (SalesOrderNum.equalsIgnoreCase("SV")) || (SalesOrderNum.equalsIgnoreCase("CR")) || (SalesOrderNum.equalsIgnoreCase("CW"))) {
if (!prevSalesOrder.equals(SalesOrderNo)) {
IDocEl = outdoc.createElement("IDOC");
ORDERS05.appendChild(createIDocHeader(POSLOGSalesOrderNo, outdoc, EMPST, IDocEl, StoreID, true, returnChild));
prevSalesOrder = SalesOrderNo;
}
IDocEl.appendChild(createE1EDP01forReturnLineItem(outdoc, returnChild, StoreID));
}
}
}
}
}
}
}
}
}
//end of gift card
Here I am reading root node <Return> then checking whether it contains <Tender> .. If <Tender> is present ( obviously <bby:SaleTenderType> will be present).. else if <Tender> is not present, then other function is done.
I am getting Null pointer exception in this line NodeList tenderChild = Lineitems.item(z2).getChildNodes();
Kindly provide your valuable inputs
Thanks in advance..

Java - NullPointerException in a method

I'm writing a program that could manage universitary students with courses and subjects. The problem of the class I'm showing you is that when the method
public CorsoStudi(String unNomeCorso, ArrayList unElencoMaterie, int unIdCorso)
is called it throws a NullPointerException at line elencoEsamiDati.add(q);. So, probably the problem is with this line and the line after this:
EsameDato q = new EsameDato(unElencoMaterie.get(contatore), 0);
Eclipse doesn't advice error on writing code.
Creatore.java
import java.util.ArrayList;
import java.util.Scanner;
public class Creatore {
int counterStudenti = 0;
int counterMaterie = 0;
int counterCorsi = 0;
//int counterEsami = 0;
ArrayList<Studente> listaStudenti = new ArrayList<Studente>();
ArrayList<Materia> listaMaterie = new ArrayList<Materia>();
ArrayList<CorsoStudi> listaCorsi = new ArrayList<CorsoStudi>();
//ArrayList<EsameDato> listaEsami = new ArrayList<EsameDato>();
public void iscriviStudente(String nomeStudente, String cognomeStudente, CorsoStudi corsoStudente){
listaStudenti.add(new Studente(nomeStudente, cognomeStudente, counterStudenti, corsoStudente));
counterStudenti++;
}
public void reimmatricolaStudente(int unaMatricola, int unIdCorso){
int c = 0;
CorsoStudi unCorso = null;
for(c = 0; c < listaCorsi.size(); c++){
if(listaCorsi.get(c).getIdCorso() == unIdCorso)
unCorso = listaCorsi.get(c);
}
int contatore = 0;
for(contatore = 0; contatore < listaStudenti.size(); contatore++)
if(listaStudenti.get(contatore).getMatricola() == unaMatricola){
iscriviStudente(listaStudenti.get(contatore).getNome(), listaStudenti.get(contatore).getCognome(), unCorso);
rimuoviStudente(unaMatricola);
};
}
public void rimuoviStudente(int matricola){
int contatore;
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getMatricola() == matricola)
listaStudenti.remove(contatore);
}
}
public Materia creaMateria(String nomeMateria, int crediti){
listaMaterie.add(new Materia( nomeMateria, crediti, counterMaterie));
counterMaterie++;
return listaMaterie.get(counterMaterie - 1);
}
public void creaCorsoStudi(String nomeCorso, ArrayList<Materia> materieCorso){
CorsoStudi q = new CorsoStudi( nomeCorso, materieCorso, counterCorsi);
listaCorsi.add(q);
counterCorsi++;
}
public ArrayList<Studente> cercaStudente(int opzione, String pattern){
int contatore = 0;
ArrayList<Studente> listaRicercati = new ArrayList<Studente>();
//opzione 1 = ricerca per nome
if(opzione == 1)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getNome().equalsIgnoreCase(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 2 = ricerca per cognome
if(opzione == 2)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getCognome().equalsIgnoreCase(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 3 = ricerca per matricola
if(opzione == 3)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getMatricola() == Integer.parseInt(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 4 = ricerca per corsoStudi
if(opzione == 4)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getCorsoStudi().getIdCorso() == Integer.parseInt(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
return listaRicercati;
}
public Materia materiaDaId(int id){
int c = 0;
Materia materiaDaRitornare = null;
for(c = 0; c < listaMaterie.size(); c++){
if(listaMaterie.get(c).getIdMateria() == id)
materiaDaRitornare = listaMaterie.get(c);
}
return materiaDaRitornare;
}
}
CorsoStudi.java
import java.util.ArrayList;
import java.util.Scanner;
public class CorsoStudi {
private String nomeCorso;
private int idCorso;
private ArrayList<Materia> elencoMaterie;
private ArrayList<EsameDato> elencoEsamiDati;
public CorsoStudi(String unNomeCorso, ArrayList<Materia> unElencoMaterie, int unIdCorso){
nomeCorso = unNomeCorso;
elencoMaterie = unElencoMaterie;
idCorso = unIdCorso;
int contatore = 0;
//EsameDato q = null;
for(contatore = 0; contatore < unElencoMaterie.size(); contatore++){
EsameDato q = new EsameDato(unElencoMaterie.get(contatore), 0);
elencoEsamiDati.add(q);
};
}
public String getNomeCorso(){
return nomeCorso;
}
public int getIdCorso(){
return idCorso;
}
public ArrayList<Materia> getElencoMaterie(){
return elencoMaterie;
}
public ArrayList<EsameDato> getElencoEsamiDati(){
return elencoEsamiDati;
}
public String toString(){
String s = "";
s = s + "Ecco le materie di questo Corso di Studi:\n";
int c = 0;
for(c= 0; c < elencoMaterie.size(); c++){
s = s + elencoMaterie.get(c).getIdMateria() + " ";
s = s + elencoMaterie.get(c).getNomeMateria() + " (";
s = s + elencoMaterie.get(c).getCrediti() + " crediti)\n";
}
return s;
}
}
You have not initialized the field elencoEsamiDati therefore the actual value is null.
Before adding elements to an ArrayList you need to create it:
private ArrayList<EsameDato> elencoEsamiDati = new ArrayList<EsameDato>();
You may also need to initialize other fields as well.
BTW it is not a good idea to use your own language when programming, use English instead.

Categories