I wrote a program who simulate a card game.
I choose some values for the colors of the card and some values for values of the cards.
I wrote my own Exception, is CarteException.java who have two child, CarteValeurException.java and CarteCouleurException.java depending on the type of Exception at the initialisation of a Carte
If the value of the color is not in 1 or 4, that will be throw an Exception of CarteCouleurExeception.java and same for the other Exception, if the value are not 1 or in 7 and 13, that will be throw a CarteValeurException.java
This is my code for the class Carte.java :
public Carte(int coul, int val) throws CarteException {
if(coul < 1 || coul > 4) {
throw new CarteCouleurException("Erreur d'initialisation lors de la création d'une carte.",coul);
}
if(val < 1 || (val > 1 && val < 7) || val > 13) {
throw new CarteValeurException("Erreur d'initialisation lors de la création d'une carte.",val);
}
this.couleur = coul;
this.valeur = val;
}
This is the code for the Class CarteException.java :
public class CarteException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
protected String message;
protected CarteException() {
this.message = "";
}
public CarteException(String chaine) {
this.message = chaine;
}
public String getMessage() {
return (this.message + " : Erreur non spécifiée de valeur ou de couleur de carte.");
}
}
And finally, the initialisation of a card in Belote.java :
package TP.TP6.Exercice2;
import java.util.Random;
import java.util.Vector;
import java.util.Stack;
import TP.TP5.Exercice1.Question4.Carte;
public class Belote {
private Stack<Carte> tasDistibution;
private Vector<Stack<Carte>> mainsJoueurs;
private Vector<Stack<Carte>> plisJoueurs;
public Belote() {
this.tasDistibution = new Stack<Carte>();
this.mainsJoueurs = new Vector<Stack<Carte>>(4);
this.plisJoueurs = new Vector<Stack<Carte>>(4);
for(int i = 0 ; i < 4 ; i++) {
this.mainsJoueurs.add(i, new Stack<Carte>());
this.plisJoueurs.add(i, new Stack<Carte>());
}
}
private void initialiserTasDistribution() throws CarteException {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= 13; j++) {
try {
//Initialisation right here
this.tasDistibution.push(new Carte(i,j));
}
catch(CarteException CE) {
System.err.println("Erreur : " + CE);
}
}
}
}
private void couper() {
Stack<Carte> tas1 = new Stack<Carte>();
Stack<Carte> tas2 = new Stack<Carte>();
Random r = new Random();
int coupe = 1 + r.nextInt(33 - 1);
for (int i = 0; i < coupe; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas1.push(carte);
}
while (tasDistibution.isEmpty() == false) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas2.push(carte);
}
while (tas1.isEmpty() == false) {
Carte carte = tas1.peek();
tas1.pop();
this.tasDistibution.push(carte);
}
while (tas2.isEmpty() == false) {
Carte carte = tas2.peek();
tas2.pop();
this.tasDistibution.push(carte);
}
}
private void melanger(int nbMelange) {
Carte tabcarte[] = new Carte[32];
for (int i = 0; i < tabcarte.length; i++) {
Carte cartesommet = this.tasDistibution.peek();
this.tasDistibution.pop();
tabcarte[i] = cartesommet;
}
for (int i = 0; i < nbMelange; i++) {
Random r = new Random();
int pos1 = 1 + r.nextInt(32 - 1);
int pos2 = 1 + r.nextInt(32 - 1);
if (pos1 == pos2) {
System.out.println("Pas de chance");
} else {
Carte temp;
temp = tabcarte[pos1];
tabcarte[pos1] = tabcarte[pos2];
tabcarte[pos2] = temp;
}
}
for (int i = 0; i < tabcarte.length; i++) {
Carte carte = tabcarte[i];
this.tasDistibution.push(carte);
}
}
private void donnerCartesAJoueur(int nbcartedonnes, int numjoueur) {
for (int i = 0; i < nbcartedonnes; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
Stack<Carte> stack = this.mainsJoueurs.get(numjoueur);
stack.push(carte);
this.mainsJoueurs.set(numjoueur, stack);
}
}
private void distribuer() {
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(2, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
System.out.println("\n\nDistribution pour joueur : " + (i+1) + " \n\nMain du joueur : " + (i+1));
System.out.println(this.mainsJoueurs.get(i).toString());
}
}
private void assemblerPlisJoueur() {
for (int i = 0; i < 4; i++) {
while (this.plisJoueurs.get(i).isEmpty() == false) {
Carte carte = this.plisJoueurs.get(i).peek();
Stack<Carte> stack = this.plisJoueurs.get(i);
stack.pop();
this.plisJoueurs.set(i, stack);
this.tasDistibution.push(carte);
}
}
}
private void preparerPremiereManche() throws CarteException {
try {
this.initialiserTasDistribution();
}
catch(CarteException CE) {
System.err.println("Erreur d'initilisation du tas à distribuer.");
throw CE;
}
this.melanger(32);
this.couper();
this.distribuer();
}
private void preparerMancheSuivante() {
this.assemblerPlisJoueur();
this.couper();
this.distribuer();
}
private void jouerPli() {
Stack<Carte> tasIntermediaire = new Stack<Carte>();
for (int i = 0; i < 4; i++) {
Carte carte = this.mainsJoueurs.get(i).peek();
Stack<Carte> stack = this.mainsJoueurs.get(i);
stack.pop();
this.mainsJoueurs.set(i, stack);
tasIntermediaire.push(carte);
}
Random r = new Random();
int gagnant = 0 + r.nextInt(4 - 0);
System.out.println("Le joueur " + (gagnant+1) + " a gagné ce pli");
for (int i = 0; i < 4; i++) {
Carte carte = tasIntermediaire.peek();
tasIntermediaire.pop();
Stack<Carte> stack = this.plisJoueurs.get(gagnant);
stack.push(carte);
this.plisJoueurs.set(gagnant, stack);
}
System.out.println("Pli du joueur " + (gagnant+1));
System.out.println(this.plisJoueurs.get(gagnant).toString());
}
private void jouerManche(int nbPlis) {
for (int i = 1; i <= nbPlis; i++) {
System.out.println("\n\nPli numéro : " + i);
this.jouerPli();
}
this.preparerMancheSuivante();
}
public void jouerPartie(int nbManches) throws CarteException {
try {
this.preparerPremiereManche();
}
catch(CarteException CE) {
System.err.println("Erreur d'initialisation de la première manche");
throw CE;
}
for (int i = 1; i <= nbManches; i++) {
System.out.println("\n\nManche numéro : " + i);
this.jouerManche(8);
}
System.out.println("Jeu terminé");
}
}
The problem is in Belote.java, Eclipse send me an error like this here catch(CarteException CE) :
Unreachable catch block for CarteException. This exception is never thrown from the try statement body
But i put right : public Carte(int coul, int val) throws CarteException in the first class so don't understand the problem.
I wrote the class CarteValeurException.java and CarteCouleurException.java but that is practically the same than CarteException.java so that's why i don't put the code of the class right here.
Thank you for your help !
You have to throw or catch your exception.
The signature of your method is:
private void initialiserTasDistribution() throws CarteException
So when the exception is trowed from the constructor in Carte is re-throwed by your method. Thus the catch is unreachable. You have to chose the best approach for your code.
Here a set of rules of thumb: Throws or try+catch
Your problem is that your method is declared to propagate the exception higher up the call stack:
private void initialiserTasDistribution() throws CarteException {
This means that whoever calls the method initialiserTasDistribution will have to handle this exception instead (or do the same and propagate it even higher). It is a form of deferring responsibility. It's saying "I'm not going to handle this error, someone else can".
This directly contradicts the implementation of your method because you do in fact handle the error.
try {
this.tasDistibution.push(new Carte(i,j));
}
catch(CarteException CE) {
System.err.println("Erreur : " + CE);
}
If you change your method signature to remove the throws declaration, you should be okay:
private void initialiserTasDistribution() {
Related
The following is my Brute force code for Sudoku:
public abstract class SudokuBoard
{
protected int ROWS = 9;
protected int COLS = 9;
int solutionsCounter;
double startTime;
double endTime;
String[] data = new String[8];
int puzzleNum = countTotalRows();
// data accessors
public abstract int get(int r, int c);
public abstract void set(int r, int c, int v);
// specific constraints checker, returns true even if the values are not complete
abstract boolean isRowCompatible(int r, int c);
abstract boolean isColCompatible(int r, int c);
abstract boolean isBoxCompatible(int r, int c);
// returns true if element S[r,c] is compatible, even if some values arount it are not filled
public boolean isCompatible(int r, int c)
{
for (int i=0; i<ROWS; i++)
for (int j=0; j<COLS; j++)
if(! (isRowCompatible(r, c) && isColCompatible(r, c) && isBoxCompatible(r, c)))
return false;
return true;
}
// this is the one called to solve the sudoku
public void solve()
{
//convert to seconds
startTime = System.nanoTime() / 1000000000.0;
solve(1,1);
}
// function to incorporate clues
public void incorporateClues(int[] clues)
{
for (int i=0; i<clues.length; i++)
set(clues[i]/100, (clues[i]%100)/10, clues[i]%10);
}
// the recursive backtracking function that does the hardwork
void solve(int r, int c)
{
while (((System.nanoTime() / 1000000000.0) - startTime) < 10) {
System.out.println("Time: " + ((System.nanoTime() / 1000000000.0) - startTime));
if (r<=9 && c<=9)
{
if (get(r,c) == 0)
{
for (int v=1; v<=COLS; v++)
{
set(r,c,v);
if (isCompatible(r,c))
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
set(r, c, 0);
}
else
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
else
{
solutionsCounter = solutionsCounter + 1;
//convert to seconds
endTime = System.nanoTime() / 1000000000.0;
// print();
}
}
}
// sample display function
void print()
{
for(int i=1; i<=ROWS; i++)
{
for (int j=1; j<=COLS; j++)
System.out.print(get(i,j));
System.out.println();
}
System.out.println("count: " + solutionsCounter);
}
void saveData (String[] data) throws java.io.IOException
{
try
{
java.io.BufferedWriter outfile = new java.io.BufferedWriter(new java.io.FileWriter("15-clue_results.csv", true));
for (int i = 0; i < data.length; i++) {
outfile.write(String.valueOf(data[i]));
outfile.append(',');
}
outfile.append('\n');
outfile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
static int countTotalRows () {
int count = 0;
try
{
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.FileReader("15-clue_results.csv"));
String input;
while((input = bufferedReader.readLine()) != null)
{
count = count + 1;
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return count;
}
public static void main(String []arg)
{
int numClues;
try {
java.io.BufferedReader csvFile = new java.io.BufferedReader(new java.io.FileReader("clue_set"));
String dataRow;
while ((dataRow = csvFile.readLine()) != null) {
SudokuBoard board = new SB_IntMatrix();
String[] stringSet = new String[15];
int[] PUZZLE1 = new int[15];
board.puzzleNum = board.puzzleNum + 1;
stringSet = dataRow.split(" ");
for (int i = 0; i < stringSet.length; i++) {
PUZZLE1[i] = Integer.parseInt(stringSet[i]);
}
board.incorporateClues(PUZZLE1);
for (int i = 0; i < 1; i++) {
board.solutionsCounter = 0;
board.solve();
board.data[0] = Integer.toString(board.puzzleNum);
board.data[1] = dataRow;
board.data[2] = Integer.toString(board.solutionsCounter);
board.data[3 + i] = Double.toString(board.endTime - board.startTime);
}
try
{
board.saveData(board.data);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
csvFile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
The requirement is to limit the solving time of solve(int r, int c) to only 1 hour.
To do this, I tried to put it inside a while loop while (((System.nanoTime() / 1000000000.0) - startTime) < 10) . The number 10 is to just test the code.
I understand that I looped it only 5 times in main method but, it resets back to 0 always and never stops and exceeds the limit of my loop in main.
You should use a Future:
final ExecutorService executor = Executors.newFixedThreadPool(4);
final Future<Boolean> future = executor.submit(() -> {
// Call solve here
return true;
});
future.get(60, TimeUnit.MINUTES); // Blocks
You can do something like:
Init the start date:
LocalDateTime startDateTime = LocalDateTime.now();
And check if 1 hour has elapsed:
LocalDateTime toDateTime = LocalDateTime.now();
if (Duration.between(startDateTime, toDateTime).toHours() > 0) {
// stop the execution
}
This ClassCastException is driving me crazy.
When invoking the method insert() I get this:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to Rubrica$Pair
Hope anybody can help without loosing much time :).
class Rubrica implements Dictionary
{
private Object[] v;
private int vSize;
public static int INITSIZE = 1;
/*
verifica se il dizionario contiene almeno una coppia chiave/valore
*/
public Rubrica()
{
v = new Object[INITSIZE];
makeEmpty();
}
private Object[] resize(Object[] v, int length)
{
Object[] newv = new Object[length * 2];
System.arraycopy(v, 0, newv, 0, length);
return newv;
}
/*
svuota il dizionario
*/
public void makeEmpty()
{
for(int i = 0; i < v.length; i++)
v[i] = new Pair(null, -1);
vSize = 0;
}
/*
Inserisce un elemento nel dizionario. L'inserimento va sempre a buon fine.
Se la chiave non esiste la coppia key/value viene aggiunta al dizionario;
se la chiave esiste gia' il valore ad essa associato viene sovrascritto
con il nuovo valore; se key e` null viene lanciata IllegalArgumentException
*/
private Object[] insertionSort(Object[] v, int vSize)
{
for(int i = 0; i < vSize; i++)
{
Comparable temp = ((Pair)v[i]).getName();
int j;
for(j = i; j > 0 && temp.compareTo(((Pair)v[j - 1]).getName()) < 0; j--)
v[j] = v[j - 1];
v[j] = temp;
}
return v;
}
public void insert(Comparable key, Object value)
{
if(vSize == v.length)
v = resize(v, vSize);
if(key.equals(null))
throw new IllegalArgumentException();
int index = binaryKeyIndexSearch(v, vSize, key);
if(index == -1)
v[vSize++] = new Pair((String)key, (long)value);
else
v[index] = new Pair((String) key, (long)value);
v = insertionSort(v, vSize);
}
/*
Cerca nel dizionario l'elemento specificato dalla chiave key
La ricerca per chiave restituisce soltanto il valore ad essa associato
Se la chiave non esiste viene lanciata DictionaryItemNotFoundException
*/
private int binaryKeyIndexSearch(Object[] v, int vSize, Comparable value)
{
return binKeySearch(v, 0, vSize - 1, value);
}
private int binKeySearch(Object[] v, int from, int to, Comparable value)
{
if(from > to)
return -1;
int mid = (from + to) / 2;
Comparable midValue = ((Pair)v[mid]).getName(); //errore
if(value.compareTo(midValue) == 0)
return mid;
else if(value.compareTo(midValue) < 0)
return binKeySearch(v, from, mid - 1, value);
else
return binKeySearch(v, mid + 1, to, value);
}
//classe privata Pair: DO NOT MODIFY!!
private class Pair
{ public Pair(String aName, long aPhone)
{ name= aName;
phone = aPhone;
}
public String getName()
{ return name; }
public long getPhone()
{ return phone; }
/*
Restituisce una stringa contenente
- la nome, "name"
- un carattere di separazione ( : )
- il numero telefonico, "phone"
*/
public String toString()
{ return name + " : " + phone; }
//campi di esemplare
private String name;
private long phone;
}
}
The problem is in this method:
private Object[] insertionSort(Object[] v, int vSize)
{
for(int i = 0; i < vSize; i++)
{
Comparable temp = ((Pair)v[i]).getName();
int j;
for(j = i; j > 0 && temp.compareTo(((Pair)v[j - 1]).getName()) < 0; j--)
v[j] = v[j - 1];
v[j] = temp;
}
return v;
}
Look closely, you write to temp the name of v[i] and then assign temp to v[j]so now you have String instead of Pair in v[j].
You could get rid of ClassCastExceptions if you have used the correct type for your array, which is Pair[]. I mean if you swap all Object[] to Pair[] you will see this kind of incorrect assignment in compile time, not in runtime.
I am trying to make a game which breaks the tile when I type a specific key.
Firstly, here is what the exception.
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
at sun.nio.cs.UTF_8.access$200(UTF_8.java:57)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:636)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.PrintStream.newLine(PrintStream.java:545)
at java.io.PrintStream.println(PrintStream.java:807)
at code.gui.NewView.addTileToDelete(NewView.java:192)
at code.gui.NewView.deleteTileByColor(NewView.java:151)
at code.gui.NewView.deleteTileByColor(NewView.java:158)
at code.gui.NewView.deleteTileByColor(NewView.java:152)
It runs fine if I execute deleteTileByColor method once,
however from the second time, above error occurs.
Here's the code for game.
package code.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import code.handlers.PressKeyHandler;
import code.model.DataModel;
import code.parts.GamePanel;
import code.parts.GameTile;
public class NewView extends JFrame {
int _exitCounter;
int _tileDeleteCounter;
int _column = 4;
int _row = 4;
GamePanel _gamePanel;
DataModel _dm;
GameTile _tile;
ArrayList<ArrayList<GameTile>> _gameTileList = new ArrayList<ArrayList<GameTile>>();
ArrayList<GamePanel> _gamePanLst = new ArrayList<GamePanel>();
ArrayList<Character> _letterList;
public NewView(DataModel dm) {
super("Sequence Game");
this._dm = dm;
setLayout(new GridLayout(1, 4));
shuffleLetter();
for (int i = 0; i < _column; i++) {
_gamePanel = new GamePanel();
System.out.println("1. _gameTileList에 new ArrayList 총 " + i + "개 추가");
for (int j = 0; j < _row; j++) {
_tile = new GameTile(_letterList.get((4 * i) + j));
_gamePanel.add(_tile);
_tile.addKeyListener(new PressKeyHandler(_dm));
}
_gamePanLst.add(_gamePanel);
}
System.out.println("어레이 리스트<어레이리스트> 사이즈 : " + _gameTileList.size());
setFrame();
this.setSize(300, 500);
this.setVisible(true);
this.add(_gamePanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_dm.setView(this);
}
public void setFrame() {
for (int i = 0; i < _gamePanLst.size(); i++) {
this.add(_gamePanLst.get(i), i);
}
this.repaint();
this.revalidate();
}
public void update(char letter) {
resetTileArrLst();
Color tileColor;
for (int i = 0; i < _column; i++) {
for (int j = 0; j < _row; j++) {
if (_gamePanLst.get(i).getComponent(j).getName().equals("" + letter)) {
System.out.println("i : " + i + " / j : " + j);
// System.out.println("최초비교");
tileColor = setTileColor(_gamePanLst.get(i).getComponent(j));
addTileToDelete(i, j);
deleteTileByColor(i, j, tileColor);
}
}
}
checkToQuit();
setFrame();
}
public void shuffleLetter() {
ArrayList<Character> temp = new ArrayList<Character>();
int numOfLetters = 26;
for (int i = 0; i < numOfLetters; i++) {
temp.add((char) (97 + (i)));
}
Collections.shuffle(temp);
_letterList = temp;
}
public Color setTileColor(Component comp) {
System.out.println("**********setTileColor********** ");
System.out.println("compo color : " + comp.getBackground());
Color temp;
if (comp.getBackground().equals(Color.RED)) {
temp = Color.RED;
} else if (comp.getBackground().equals(Color.BLUE)) {
temp = Color.BLUE;
} else if (comp.getBackground().equals(Color.YELLOW)) {
temp = Color.YELLOW;
} else {
temp = Color.GREEN;
}
return temp;
}
public GameTile getEmptyTile() {
GameTile emptyTile = new GameTile(' ');
emptyTile.setBorder(BorderFactory.createEmptyBorder());
emptyTile.setBackground(Color.BLACK);
emptyTile.addKeyListener(new PressKeyHandler(_dm));
return emptyTile;
}
public void checkToQuit() {
int counter = 0;
for (int i = 0; i < _gamePanel.getComponentCount(); i++) {
if (_gamePanel.getComponent(i).getBackground() == Color.BLACK) {
counter++;
}
}
if (counter == _gamePanel.getComponentCount()) {
this.dispose();
}
}
public void deleteTile(int i) {
_gamePanel.remove(i);
_gamePanel.add(getEmptyTile(), i);
}
public void deleteTileByColor(int column, int row, Color tileColor) {
// Right
if (((column + 1) < 4) && tileColor == (_gamePanLst.get((column + 1)).getComponent(row).getBackground())) {
column = column + 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Left
if ((column - 1 >= 0) && tileColor == (_gamePanLst.get(column - 1).getComponent(row).getBackground())) {
column = column - 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Below
if ((row + 1 < 4) && tileColor == (_gamePanLst.get(column).getComponent(row + 1).getBackground())) {
row = row + 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Above
if ((row - 1 >= 0) && tileColor == (_gamePanLst.get(column).getComponent(row - 1).getBackground())) {
row = row - 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
moveDownTiles();
}
public void moveDownTiles() {
for (int i = 0; i < _column; i++) {
for (int j = 0; j < _row; j++) {
if (_gamePanLst.get(i).getComponent(j).equals(_gameTileList.get(i).get(j))) {
_gamePanLst.get(i).remove(j);
_gamePanLst.get(i).add(getEmptyTile(), 0);
}
}
}
resetTileArrLst();
}
public void addTileToDelete(int column, int row) {
_gameTileList.get(column).set(row, (GameTile) _gamePanLst.get(column).getComponent(row));
System.out.println("지울 타일 추가 완료 : " + _gamePanLst.get(column).getComponent(row).getName());
}
public int get_exitCounter() {
return _exitCounter;
}
public void set_exitCounter(int _exitCounter) {
this._exitCounter = _exitCounter;
}
public GamePanel get_gamePanel() {
return _gamePanel;
}
public void set_gamePanel(GamePanel _gamePanel) {
this._gamePanel = _gamePanel;
}
public ArrayList<ArrayList<GameTile>> get_gameTilesList() {
return _gameTileList;
}
public void set_gameTilesList(ArrayList<ArrayList<GameTile>> _gameTilesList) {
this._gameTileList = _gameTilesList;
}
public ArrayList<Character> get_letterList() {
return _letterList;
}
public void set_letterList(ArrayList<Character> _letterList) {
this._letterList = _letterList;
}
public ArrayList<GamePanel> get_gamePanLst() {
return _gamePanLst;
}
public void set_gamePanLst(ArrayList<GamePanel> _gamePanLst) {
this._gamePanLst = _gamePanLst;
}
public void resetTileArrLst() {
if (_gameTileList.size() != 0) {
_gameTileList.clear();
}
for (int i = 0; i < _column; i++) {
_gameTileList.add(i, new ArrayList<GameTile>());
for (int j = 0; j < _row; j++) {
_gameTileList.get(i).add(getEmptyTile());
}
}
}
}
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..
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.