+ 1
Nullpointer exeption?
I tried to make a gambling game, that either doubles your money or cuts it in half. I am getting a nullpointer exception error and I don't know why. Here is the code: package programlearning; import java.util.Scanner; import java.util.Random; public class Gambling { private static Scanner money; private static Random Randomgen; public static void main(String[] args) { int y = money.nextInt(); System.out.println("Input starting money"); while(y > 1){ int x = Randomgen.nextInt(1); if(x == 1){ y /= 2; System.out.println("Your money" + y); } else y *= 2; System.out.println("Your money" + y); } } }
1 Odpowiedź
+ 1
I'm not sure what you want to do, but I suppose you forgot to create money and Randomgen object, + Randomgen is a bad codding style, replace it with randomgen.
Here is your edited code:
import java.util.Scanner;
import java.util.Random;
public class Gambling {
private static Scanner money;
private static Random randomgen;
public static void main(String[] args) {
money = new Scanner(System.in);
randomgen = new Random();
System.out.println("Input starting money");
int y = money.nextInt();
while (y > 1) {
int x = randomgen.nextInt(1);
if (x == 1) {
y /= 2;
System.out.println("Your money" + y);
} else
y *= 2;
System.out.println("Your money" + y);
}
}
}