public static void startGame(){
//int stone = 0, diamond = 0, iron = 0, gold = 0;
StringBuffer blockys = new StringBuffer("\uD83E\uDDCD ▯▯▯▯▯▯▯▯▯");
Scanner input = new Scanner(System.in);
System.out.println("\uD83E\uDDCD " + "▯▯▯▯▯▯▯▯▯" + "\n");
String user = input.next();
boolean game = true;
while(game) {
switch (user) {
//Code
case "M":
System.out.println(mine(blockys));
user = input.next();
break;
}
}
public static StringBuffer mine(StringBuffer blockys){
addOre(blockys);
blockys.delete(2, 3);
int randBlock = (int) (Math.random() * 101) + 0;
//Code
else{
//add bomb 5% chance
blockys.append("\uD83E\uDDE8");
}
return blockys;
}
public static void addOre(StringBuffer blockys){
String str = blockys.substring(2, 3);
switch(str){
//Code
case "\uD83E\uDDE8":
System.out.println("You mined a bomb! BOOOOOOOM! You died!");
System.exit(0);
break;
}
}
In my method addOre, when it reaches the case "\uD83E\uDDE8" it does not print out to the console nor does it terminate the program. When it gets to the case, it completely ignores it and the program continues. I have tried making it into a default which fails, and have tried different variables in the cases, yet it never prints anything. How can I fix it so that it prints and terminates after?
Its a 'length' problem.
Consider the following code:
public static void main(String[] args) {
System.out.println("Hello".substring(2, 3).length());
System.out.println("\uD83E\uDDE8".length());
}
Will output:
1
2
So what the problem ?
When you a substring, you will always be returning a string with a length of 1.
While on the other end, in your switch case, you are trying to test a string with a length of 2.
1 != 2: condition never met