Getting a NullPointerException, not sure why - java

First I instantiate a gamestate
class GameState extends state{
ArrayList<Level> levels;
int currentLevelID;
public GameState() {
stateID = 2;
levels = new ArrayList<Level>();
createLevels();
currentLevelID = 0;
}
which creates levels
public void createLevels(){
try {
this.levels.add(new NormalLevel(0, 10, 10, null, null, new EmptyTile(1, 1, 1, 1, null) ));
} catch (IOException e) {
e.printStackTrace();
}
}
using this bit of code (forgot the technical term lol)
//level is the superclass of normallevel or whatever i named the default level
public Level(int id, int height, int width, ArrayList<TileEntity> tiles, ArrayList<MobileEntity> mobiles, TileEntity fillBlock){
this.height = height;
this.levelID = id;
this.width = width;
if(tiles != null){
this.tiles = tiles;
} else {
tiles = new ArrayList<TileEntity>();
try {
tiles.add(new EmptyTile(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fillBlock != null){
this.tiles = new ArrayList<TileEntity>();
this.fillWith(fillBlock);
}
}
public void fillWith(TileEntity tile){
for(int i = 0; i < this.height; i++){
for(int j = 0; j < this.width; j++){
for(int k = 0; k < this.tiles.size(); k++){
if (this.tiles.get(k).y == i && this.tiles.get(k).x == j){
break;
}
if(k == this.tiles.size()){
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
}
}
}
}
Then I try to update the level
public void update(){
this.draw();
for(int i = 0; i < this.tiles.size(); i++){
this.tiles.get(i).update();
}
for(int i = 0; i < this.mobiles.size(); i++){ //nullpointerexception here
this.mobiles.get(i).update();
}
this.specialUpdate();
}
But I get an error on the commented line. I'm confused as hell, help would be appreciated :)

Your mobiles object is null because in the following code
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
in the else case your assigning the local variable mobiles rather than this.mobiles

if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If mobiles != null you assign the instance variable (this.mobiles), yet if they are, you create a new List, but assign it to the local variable (mobiles), which is why the list never reaches the instance variable.

Related

changing midi volume in java

first of all changing volume is working but i got some problems while changing the volume so 1) after changing the volume like setting it to 0 (no volume) you still hearing parts of the song in the default value of the volume 2)after song changed the volume getting back to the default value of the volume
public static void setVolume(double value) {
System.out.println();
int CHANGE_VOLUME = 7;
midivol =(value);
try {
if (synthesizer.getDefaultSoundbank() == null) {
System.out.println(444);
ShortMessage volumeMessage = new ShortMessage();
for (int i = 0; i < 16; i++) {
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, CHANGE_VOLUME,(int)(value * 127.0));
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, 39, (int)(value * 127.0));
MidiSystem.getReceiver().send(volumeMessage, -1);
}
} else {
MidiChannel[] channels = synthesizer.getChannels();
for( int c = 0; c < channels.length; c++ ) {
if(channels[c] != null) channels[c].controlChange( 7, (int)( value*127.0) );
}
}
music.setSequence(sequence);
} catch (Exception e) {
e.printStackTrace();
}
}
playing midi:
private void playMidi(String location) {
double gain =Slider.musicvolume;
music = null;
//synthesizer = null;
sequence = null;
File midiFile = new File(location);
try {
sequence = MidiSystem.getSequence(midiFile);
music = MidiSystem.getSequencer(false);
music.open();
music.setSequence(sequence);
} catch (Exception e) {
System.err.println("Problem loading MIDI file.");
e.printStackTrace();
return;
}
if (music instanceof Synthesizer) {
synthesizer = (Synthesizer) music;
} else {
try {
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
if (synthesizer.getDefaultSoundbank() == null) {
music.getTransmitter().setReceiver(MidiSystem.getReceiver());
} else {
music.getTransmitter().setReceiver(synthesizer.getReceiver());
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
MidiChannel[] channels = synthesizer.getChannels();
for (int i = 0; i < channels.length; i++) {
channels[i].controlChange(7, (int) (gain * 127.0));
}
try {
music.setSequence(sequence);
} catch (InvalidMidiDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
music.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
music.start();
}
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, CHANGE_VOLUME,(int)(value * 127.0));
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, 39, (int)(value * 127.0));
MidiSystem.getReceiver().send(volumeMessage, -1);
This code sends one message. The contents of that message are the values set by the second setMessage call, so the volume MSB is not changed at all.
(And this is the wrong way of computing the LSB.)
Controller 7 is indeed for volume, but there is no exact standard for how the values are to be interpreted. Apparently, your synthesizer does not mute itself when it receives a volume of zero.
Many MIDI files do their own changes to controller 7. If your synthesizer supports Master Volume, you should send that instead.

how to return string value out of for loop scope

I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}

java: check boolean in for loop

If work.length is 4 ,
I have to check the AResult in for loop
If 4 AResult all are true ,set result.setstatus("success");
or result.setstatus("fail");
What can I do ??
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
//result.setstatus("success"); //all true
//result.setstatus("fail");
Add a counter. Increment it when your condition is true. Check the value of the counter after your loop. Something like
int counter = 0;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start");
if (AResult) {
counter++;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if (work.length == 4 && counter == 4) {
result.setstatus("success");
} else {
result.setstatus("fail");
}
You could optimize the above (and reduce the code size) with something like
int counter = 0;
if (work.length == 4) { // <-- check the length first
for (int i = 0; i < work.length; i++) {
if (!work[i].contains("#")) {
CommandLineInterface CLI = new CommandLineInterface();
try {
if (CLI.Setting(work[i], "start")) {
counter++; // <-- increment the counter.
} else {
break; // <-- break on any fale.
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
result.setstatus(counter == 4 ? "success" : "fail"); // <-- setstatus
try this, you really don't need to iterate the loop till end when a false condition is encountered in between
//initially set success
result.setstatus("success");
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
try {
if(CLI.Setting(work[i],"start"))
{
result.setstatus("fail");
//no need to iterate further
break;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
You can also try the following code
boolean statusFlag = true;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
if(!AResult){
statusFlag = false;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if(statusFlag){
result.setstatus("success");
}else{
result.setstatus("fail");
}
}

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Why does a integer, after put into an array, change values?

SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.

Categories