C# DataTable XML Equivalent in java - java

public Dictionary<string, SomeObject> DictionaryVar= new Dictionary<string, SomeObject>();
foreach (SomeObject ojv in DictionaryVar.Values)
{
if (dt.Rows.Find(obj.FirstName()) == null)
{
dt.Rows.Add(new object[] { false, obj.FirstName(), "", "", 0 });
}
}
I have tried this but its not working.. I am trying to populate jtable by looping through some objects by checking whether the field exists if it doesn't , then i add it to the table.
for (SomeObject bs : DictionaryVar.values()) {
System.out.println("not getting inside");
for (int i = 0; i < jTable1.getRowCount(); i++) {
if (!jTable1.getValueAt(i, 1).equals(bs.FirstName())) {
((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{false, bs.FirstName(), "", "", 0, ""});
} else {
}
}
}

System.out.println("the program is outputing this");
if (ListBookMark.size() > 0) {
for (SomeObject bs : DictionaryVar.values()) {
System.out.println("working now");
if (jTable1.getModel().getColumnName(1).equalsIgnoreCase(bs.GetName()) == false) {
((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{false, bs.GetName(), "", "", 0, ""});
}
}
}else {
System.out.println("bs size = " + (ListBookMark.size() ));
}

Related

Java to Excel: How to get value from main class to excel class in column B?

Excel: I want to take the variable value from "name", "number" and "country" from main class to excel class? Instead of column B: "Johan Svenson" 250 and "SWE"
Main class
Take value from "Name, "Number" and "country" from main class to excel class
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MainProgramPA {
private static Scanner scan = new Scanner(System.in);
private static List<Contestant> scoreboard = new ArrayList<>();
private static String[] heptathlon = { "100 m hurdles", "High jump", "Shot put", "200 m", "Long jump",
"Javelin throw", "800 m" };
private static ScoreCalculator calc = new ScoreCalculator();
private static String mainEvent = "Heptathlon";
//private static Excel excel = new Excel();
public static void main(String[] args) {
contestantInput();
resultInput();
}
private static void contestantInput() {
int contestants = 0;
while (true) {
if (contestants < 40) {
System.out.println("Input the contestants name. Or input Exit to stop inputting contestants.");
String name = scan.nextLine();
if (name.equalsIgnoreCase("Exit")) {
break;
}
System.out.println("Input the contestants countrys alpha-3 code.");
String country = scan.nextLine();
System.out.println("Input the contestants number.");
int number = Integer.valueOf(scan.nextLine());
Contestant competitor = new Contestant(name, number, country);
scoreboard.add(competitor);
} else {
break;
}
contestants++;
}
}
private static void resultInput() {
System.out.println(
"The result should be measured in seconds (running), metres (throwing) or centimetres (jumping). \n");
if (mainEvent.equalsIgnoreCase("Decathlon")) {
for (int i = 0; i < decathlon.length; i++) {
for (int j = 0; j < scoreboard.size(); j++) {
System.out.println("Input the result " + scoreboard.get(j).getName() + " got on the " + decathlon[i]
+ " event. Or write exit to stop the program.");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Exit")) {
i = 15;
break;
} else {
double result = Double.valueOf(input);
int score = calc.eventScoreCalculation("Decathlon", decathlon[i], result);
scoreboard.get(j).addSportEvent(decathlon[i], score, result);
System.out.println(score);
}
}
System.out.println("Input scoreboard if you want to see the scores. Input anything else to continue.");
String choice = scan.nextLine();
if (choice.equalsIgnoreCase("Scoreboard")) {
ConsoleOutput.printResultTable(scoreboard);
}
}
} else if (mainEvent.equalsIgnoreCase("Heptathlon")) {
for (int i = 0; i < heptathlon.length; i++) {
for (int j = 0; j < scoreboard.size(); j++) {
System.out.println("Input the result " + scoreboard.get(j).getName() + " got on the "
+ heptathlon[i] + " event. Or write exit to stop the program.");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Exit")) {
i = 15;
break;
} else {
double result = Double.valueOf(input);
int score = calc.eventScoreCalculation("Heptathlon", heptathlon[i], result);
scoreboard.get(j).addSportEvent(heptathlon[i], score, result);
System.out.println(score);
}
}
System.out.println("Input scoreboard if you want to see the scores. Input anything else to continue.");
String choice = scan.nextLine();
if (choice.equalsIgnoreCase("Scoreboard")) {
ConsoleOutput.printResultTable(scoreboard);
}
}
}
}
}
Excel class
Replace value "Johan Svenson", 250 and "SWE"
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
public class Excel extends MainProgramPA {
MainProgramPA mains = new MainProgramPA();
public static void main(String[] args) {
// Create workbook in .xls format
Workbook workbook = new HSSFWorkbook();
// For .xslx workbooks use XSSFWoorkbok();
// Create Sheets
Sheet sh = workbook.createSheet("Decathlon");
Sheet sh2 = workbook.createSheet("Heptathlon");
Cell cell, cell1;
Row row, row1;
CellStyle cellStyle, cellStyle1;
Font font;
//-----------------------------------------------------------------------------------------
// Values for Column A for Heptathlon
Object columnA1[][] = { { "Name" },
{ "Number" },
{ "Country" },
{ "" },
{ "1. 100 metres hurdles" },
{ "2. High jump" },
{ "3. Shot put" },
{ "4. 200 metres" },
{ "DAY 1 TOTAL" },
{ "DAY 1 PLACE" } };
// Create Cells and Column A for Heptathlon
int rowCount0 = 0;
for (Object emp[] : columnA1) {
row = sh2.createRow(rowCount0++);
int columnCount = 0;
for (Object value : emp) {
cell = row.createCell(columnCount++);
if (value instanceof String)
cell.setCellValue((String) value);
if (value instanceof Integer)
cell.setCellValue((Integer) value);
if (value instanceof Boolean)
cell.setCellValue((Boolean) value);
// Make the column A "bold text"
cellStyle = workbook.createCellStyle();
font = workbook.createFont();
font.setBold(true);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
}
}
// Values for Column B for Heptathlon
Object columnB1[][] = { { "Johan Svensson" },
{ 250 },
{ "SWE" },
{ "RESULT", "SCORE", "PLACE" },
{ "E1 Result", "E1 Score", "E1 Place" },
{ "E2 Result", "E2 Score", "E2 Place" },
{ "E3 Result", "E3 Score", "E3 Place" },
{ "E4 Result", "E4 Score", "E4 Place" },
{ "D1 TOTAL" },
{ "D1 PLACE" } };
// Create Row and Column B for Heptathlon
int rowCount01 = 0;
for (Object emp1[] : columnB1) {
row1 = sh2.getRow(rowCount01++);
int columnCount1 = 1;
for (Object value1 : emp1) {
cell1 = row1.createCell(columnCount1++);
if (value1 instanceof String)
cell1.setCellValue((String) value1);
if (value1 instanceof Integer)
cell1.setCellValue((Integer) value1);
if (value1 instanceof Boolean)
cell1.setCellValue((Boolean) value1);
CellUtil.setAlignment(cell1, HorizontalAlignment.CENTER);
}
}
// Make the row 4 to "bold text" in Heptathlon
cellStyle1 = workbook.createCellStyle();
font = workbook.createFont();
font.setBold(true);
cellStyle1.setFont(font);
row1 = sh2.getRow(3);
cell1 = row1.getCell(0);
cell1.setCellStyle(cellStyle1);
for (int j = 0; j <= 3; j++)
row1.getCell(j).setCellStyle(cellStyle1);
// Merge cells on row 1,2,3,9,10 Column B, C and D in Heptathlon
sh2.addMergedRegion(new CellRangeAddress(0, 0, 1, 3));
sh2.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));
sh2.addMergedRegion(new CellRangeAddress(2, 2, 1, 3));
sh2.addMergedRegion(new CellRangeAddress(8, 8, 1, 3));
sh2.addMergedRegion(new CellRangeAddress(9, 9, 1, 3));
// Autosize Heptathlon-columns
for (int i = 0; i < 16; i++) {
sh2.autoSizeColumn(i);
}
try {
// Write the output to file
FileOutputStream output = new FileOutputStream("src//main//java//Deca-HeptathlonScoreboard.xls");
workbook.write(output);
output.close();
workbook.close();
System.out.println("Excel-file is Completed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think the easiest way would be to examine your access modifiers. Remember, private classes, methods, and variables can only be referenced within the context of the class they belong to.
Additionally, a static method or variable is only initialized once, at the beginning of the code execution.
I would start by examining this section here:
private static List<Contestant> scoreboard = new ArrayList<>();
Additionally, I'm not sure how your Contestant class is built, but you should have some getters and setters there to allow you to pull contestant information. So, you could so something like this in your excel class:
for (Contestant contestant : mains.scoreboard){
if (contestant.getName.equals('Johan Svensson')){
...do action here...
}
Finally, remember that declaring a variable within a loop means that variable is discarded each iteration of the loop and collected in garbage collection. So, there is no way to access those variables themselves outside of that loop.

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)

How to convert Properties class to JSON Object using JAVA

Can anyone help me? How to convert the below Input to JSON Object?
Input :
{ "details": { "device/0/endPointClientName": "ndm-xx-1", "device/1/endPointClientName": "ndm-xx-2", "EnergyMeter/0/current": "20", "EnergyMeter/0/total": "400", } }
Output:-
{ "device": [ {"endPointClientName":"ndm-xx-1" }, {"endPointClientName":"ndm-xx-2" } ], "EnergyMeter": [ {"current":"20", "total":"400"} ] }
I have the Input as JSON Object with Properties class. In the Input we are sharing the FULL PATH. we have to convert this to JSON Object.
[demo]https://jsfiddle.net/CntChen/vh7kat5a/
var input = {
"details": {
"device/0/endPointClientName": "ndm-xx-1",
"device/1/endPointClientName": "ndm-xx-2",
"EnergyMeter/0/current": "20",
"EnergyMeter/0/total": "400",
}
};
function decodeFlatObj(flatOjb) {
var outputObj = {};
for (var key in flatOjb) {
var objNow = outputObj;
var subkey = key.split('/');
for (var i = 0; i < subkey.length - 1; i++) {
// next subkey is number
if (/\d|[1-9]\d*/.test(subkey[i + 1])) {
// current subkey is number
if (/\d|[1-9]\d*/.test(subkey[i])) {
objNow.push([]);
objNow = objNow[parseInt(subkey[i])];
} else {
objNow[subkey[i]] = objNow[subkey[i]] || [];
objNow = objNow[subkey[i]];
}
} else { // next subkey is object
// current subkey is number
if (/\d|[1-9]\d*/.test(subkey[i])) {
objNow[parseInt(subkey[i])] = objNow[parseInt(subkey[i])] || {};
objNow = objNow[parseInt(subkey[i])];
} else {
objNow[subkey[i]] = objNow[subkey[i]] || {};
objNow = objNow[subkey[i]];
}
}
}
var valueDecode;
if (typeof flatOjb[key] === 'object') {
valueDecode = decodeFlatObj(flatOjb[key]);
} else {
valueDecode = flatOjb[key];
}
if (/\d|[1-9]\d*/.test(subkey[subkey.length - 1])) {
objNow[parseInt(subkey[subkey.length - 1])].push(valueDecode);
} else {
objNow[subkey[subkey.length - 1]] = valueDecode;
}
}
return outputObj;
}
var output = decodeFlatObj(input);
console.log(input);
console.log(JSON.stringify(output));
//{"details":{"device":[{"endPointClientName":"ndm-xx-1"},{"endPointClientName":"ndm-xx-2"}],"EnergyMeter":[{"current":"20","total":"400"}]}}

Return empty string if out of bounds

How would I get my program to return an empty set if a number out of bounds is entered? The class at the bottom is only a tester, so if someone were to change Jezebel to row 7, how would I keep it from crashing? Being that there are only six rows.
import java.util.Arrays;
public class Classroom {
private String[][] desks;
private String[] students = {"Todd", "Harry", "James", "Bob", "Michael",
"Fred", "Andy", "Jessica", "Kara", "Ed", "Jane", "", "Dennis", "Dwight",
"Sandy", "", "Toby", "", "Sara", "", "Randy", "", "", "", "", "John", "",
"", "", "Lindsay", "", "", "", "", "", "Marie", "", "", "", "",
"David", "", "",};
// the number of row is desks.length
// the number of column is desks[0].length
public Classroom(int row, int column) {
int i = 0;
desks = new String[row][column];
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
desks[r][c] = students[i++];
//Arrays.fill(desks[r][c], students[i++]);
}
}
}
public void setDesks(String[][] desks) {
this.desks = desks;
}
public boolean isDeskTaken(int row, int column) {
boolean taken = false;
if (desks[row][column] == "") {
taken = true;
}
if (desks[row][column].isEmpty()) {
taken = false;
}
return taken;
}
public String getRow(int row) {
String name = Arrays.toString(desks[row]);
return name;
}
public String getStudent(int row, int column) {
return desks[row][column];
}
public boolean placeStudent(int row, int column, String name) {
boolean placed = false;
// call isDeskTaken(row, column) if not
if (desks[row][column].isEmpty()) {
desks[row][column] = name;
return true;
}
return placed;
} // places student if the seat is empty
public static void main(String[] args) {
Classroom classroom = new Classroom(6, 5);
System.out.println("getRow(2)" + classroom.getRow(2));
System.out.println("placeStudent(7,1) " + classroom.placeStudent(7, 1, "Jezebel"));
System.out.println("placeStudent(4,0) " + classroom.placeStudent(4, 0, "John"));
System.out.println("Student " + classroom.getStudent(4, 1) + " has been placed in the 4th row and 1st column");
}
}
You can check the length of an array before you try and index it, like this:
String[] myArray = new String[5]; // an array with indexes [0] to [4]
// ...
// at some point we might try to access the element at index [5]
// remembering that we only have indexes [0] -> [4] in a 5 element array
// so we first check that the array is of sufficient length
if(myArray.length >= 6) {
return myArray[5]; // 6th element
} else {
return "";
}
Just to re-iterate, the length of the array is 5 elements, but the indexes of those elements are 0, 1, 2, 3, 4.

Array List value changes even when it is not changed

In the Method updateMasterGrid(),
1st I am displaying the value from c.getBall. Source is quadCellGrid arraylist
2nd I am assigning the value from quadCellGrid to mastergrid
3rd I am displaying the c.getBall.Source is quadCellGrid arraylist
After assigning the value from quadCellGrid to mastergrid. I could see the change in the value in quadCellGrid. Please check the logcat output.
Could you please let me know how to resolve this.
public class BurstBalls {
private boolean Q1Match,Q2Match,Q3Match,Q4Match;
private Texture RED_BALL;
private Texture BURST_STAR;
private List<CellGrid> masterGrid;
private List<CellGrid> quadCellGrid = new ArrayList<CellGrid>();
private List<CellGrid> burstCellGrid = new ArrayList<CellGrid>();
private SpriteBatch batch;
private float scaleXY = 0.1f;
private int Q1Moves[][] = { { 0, 0 },{ -1, 0 }, { 0, 1 }, { -1, 1 } };
private int Q2Moves[][] = { { 0, 0 },{ 1, 0 }, { 0, 1 }, { 1, 1 } };
private int Q3Moves[][] = { { 0, 0 },{ 1, 0 }, { 0,-1 }, { 1,-1 } };
private int Q4Moves[][] = { { 0, 0 },{ -1, 0 }, { 0,-1 }, { -1,-1 } };
public BurstBalls( ) {
setGameTextures();
}
public void draw(SpriteBatch sb){
batch=sb;
if(!burstCellGrid.isEmpty()){
showImageZoom1(BURST_STAR, burstCellGrid.get(0).getColCoordinate()/2, burstCellGrid.get(0).getRowCoordinate()/2);
}
}
private void showImageZoom1(Texture t, int x, int y) {
scaleXY = scaleXY + 0.05f;
if (scaleXY >= 1.0){
//burstCellGrid.clear();
scaleXY = 1.0f;
}
Sprite s = new Sprite(t);
s.setPosition(x, y);
s.setScale(scaleXY);
s.draw(batch);
}
public List<CellGrid> getMatchBallCells(int row, int col, Ball b, List<CellGrid> mGrid){
this.masterGrid=mGrid;
Q1Match=false;
Q2Match=false;
Q3Match=false;
Q4Match=false;
quadCellGrid.clear();
burstCellGrid.clear();
if(row<(MainGame.ROW-1) && col >0){
Q1Match = checkCells(b, row,col, Q1Moves);
System.out.println("Q1Match : " + Q1Match);
}
if(row<(MainGame.ROW-1) && col < (MainGame.COL-1)){
Q2Match = checkCells(b,row,col, Q2Moves);
System.out.println("Q2Match : " + Q2Match);
}
if(row>0 && col< (MainGame.COL-1)){
Q3Match = checkCells(b, row,col, Q3Moves);
System.out.println("Q3Match : " + Q3Match);
}
if(row>0 && col > 0){
Q4Match = checkCells(b, row,col, Q4Moves);
System.out.println("Q4Match : " + Q4Match);
}
if(Q1Match || Q2Match || Q3Match || Q4Match){
updateMasterGrid();
}
for (CellGrid c : burstCellGrid) {
if(c.getBall()!=null){
System.out.println("!Burst Cells - (c.getRow(),c.getCol) - " + "(" + c.getRow() +","+c.getCol() +")");
}
}
return masterGrid;
}
private void updateMasterGrid() {
for(CellGrid c: quadCellGrid){
System.out.println(" Before quadCellGrid.ball " + c.getBall());
masterGrid.get(masterGrid.indexOf(c)).setBall(null);
System.out.println(" After quadCellGrid.ball " + c.getBall());
}
}
private boolean checkCells(Ball actionBall,int row,int col,int moves[][]) {
boolean firstCell = false,secondCell = false,thirdCell = false,fourthCell = false;
CellGrid cellGrid=checkIfBallThere(row+moves[0][1],col+moves[0][0]);
firstCell = checkBall(cellGrid,actionBall);
cellGrid=checkIfBallThere(row+moves[1][1],col+moves[1][0]);
secondCell = checkBall(cellGrid,actionBall);
cellGrid=checkIfBallThere(row+moves[2][1],col+moves[2][0]);
thirdCell = checkBall(cellGrid,actionBall);
cellGrid=checkIfBallThere(row+moves[3][1],col+moves[3][0]);
fourthCell = checkBall(cellGrid,actionBall);
if(firstCell && secondCell && thirdCell && fourthCell){
return true;
}
return false;
}
private boolean checkBall(CellGrid c, Ball actionBall) {
if(c!=null && c.getBall().getTexture().equals(actionBall.getTexture())){
if (!quadCellGrid.contains(c)){
quadCellGrid.add(c);
}
return true;
}
return false;
}
public CellGrid checkIfBallThere(int cellRow, int cellCol ) {
for (CellGrid c : masterGrid) {
if (c.getRow() == cellRow && c.getCol() == cellCol
&& c.getBall() != null) {
return c;
}
}
return null;
}
private void setGameTextures() {
RED_BALL = Texturemanager.RED_BALL;
RED_BALL.setFilter(TextureFilter.Linear, TextureFilter.Linear);
BURST_STAR = Texturemanager.BURST_STAR;
BURST_STAR.setFilter(TextureFilter.Linear, TextureFilter.Linear);
}
}
Logcat
Before quadCellGrid.ball com.puzzle.game.ballpool.Ball#41414ed8
After quadCellGrid.ball null
Before quadCellGrid.ball com.puzzle.game.ballpool.Ball#41415670
After quadCellGrid.ball null
Before quadCellGrid.ball com.puzzle.game.ballpool.Ball#414155e0
After quadCellGrid.ball null
Before quadCellGrid.ball com.puzzle.game.ballpool.Ball#41415628
After quadCellGrid.ball null
A List is a list of references. If you get a reference from one list and add it to another list, both lists have references to the same object.
If you get a reference to such an object and mutate it (set a field), the change will be reflected in the relevant element of both lists.
I dont know how you have populated mastergrid and quadcellgrid, but this line seems culprit to me.
masterGrid.get(masterGrid.indexOf(c)).setBall(null);
You might be having same Cellgrid object instance stored in both MastCellGrid and Quadcellgrid, so upon printing it first, you make it null then printing it again which is printed as null.
Check or post you gird population logic.

Categories