https://www.greenfoot.org/scenarios/25669 See comments: "Known issue"
This is to be used for switching worlds. I have no problem switching from the main world to the mode selection world, but switching back is an issue. I have put in try... catch to handle the specific error I was getting, but that seems to have made it worse; it gets stuck mid-world-change without giving an error message (even though Catch is supposed to print a message in the terminal)
I am having an issue with the act method of a certain class. I want to register a single key by looping through getKey until getKey is not null, then execute a switch statement according to key = getKey (if getKey != null), switch (key). key == null even though I have put in measures to stop this.
NullPointerException: switch (key)
I printed the value for key, and for some reason it was null, even after making sure that key should not be null.
public class ModeChanger extends Actor
{
private String key = "";
/**
* Act - do whatever the ModeChanger wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
if (Greenfoot.getKey() != null){
key = Greenfoot.getKey();
if (key != null){
change();
return;
}
}
}
private void change(){
System.out.print(key);
try{
switch (key){
case "1":
Greenfoot.setWorld(new Calculator());
return;
case "2":
Greenfoot.setWorld(new ShowCalcHistory());
return;
case "3":
Greenfoot.setWorld(new ShowCalcHistory("steps"));
return;
case "4":
Greenfoot.setWorld(new ViewPronumerals());
return;
default:
break;
}
}
catch(RuntimeException error){
System.out.println("The interface you selected could not initialise in time. Please restart the program.");
error.printStackTrace();
}
}
}
