I am trying to generate random numbers (1 to 10) using enum. The variable "num" is not getting the updated random value, not sure what mistake I am making. Any pointer will be helpful. Thank you.
Java Code:
enum RandomNumbers
{
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN;
public static RandomNumbers getRandom()
{
return values()[(int)(Math.random() * values().length)];
}
}
public class RandomNumbersEnum
{
public static void main(String[] args)
{
RandomNumbers randN = RandomNumbers.getRandom();
int num = 0;
if (randN.values().equals("ONE"))
num = 1;
else if(randN.values().equals("TWO"))
num = 2;
else if(randN.values().equals("THREE"))
num = 3;
else if(randN.values().equals("FOUR"))
num = 4;
else if(randN.values().equals("FIVE"))
num = 5;
else if(randN.values().equals("SIX"))
num = 6;
else if(randN.values().equals("SEVEN"))
num = 7;
else if(randN.values().equals("EIGHT"))
num = 8;
else if(randN.values().equals("NINE"))
num = 9;
else if(randN.values().equals("TEN"))
num = 10;
System.out.println("The random number is: " + num);
}
}
You can try to use the Random class of Java, i let you some example:
Random r = new Random();
int number = r.nextInt(10)+1;
System.out.println(number);
The reason that this doesn't work is that your if statements are testing whether the array that enumerates all RandomNumbers instances is equal to some String. Of course, it never could be. When you call randN.values(), you are actually invoking the static method RandomNumbers.values(), the same method you used in your getRandom() method. If you want a string that you can compare, randN.name() would work, but it's really not a good idea.
If you insist on comparing something, you should use an identity comparison, like this:
int num; /* Notice I'm not prematurely assigning meaningless garbage here. */
if (randN == RandomNumbers.ONE)
num = 1;
else if(randN == RandomNumbers.TWO)
num = 2;
else if(randN == RandomNumbers.THREE)
num = 3;
else
throw new IllegalArgumentException("Unrecognized RandomNumber: " + randN);
The next step forward would be to use a switch statement:
int num;
switch(randN) {
case ONE: num = 1; break;
case TWO: num = 2; break;
case THREE: num = 3; break;
default: throw new IllegalArgumentException();
}
You aren't making good use of an enum. Here's an approach that takes full advantage of an enum type:
public enum RandomNumber {
ONE(1),
TWO(2),
THREE(3);
private final int value;
private RandomNumber(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public static RandomNumber roll()
{
RandomNumber[] values = values();
int idx = ThreadLocalRandom.current().nextInt(values.length);
return values[idx];
}
public static void main(String... argv)
{
RandomNumber num = RandomNumber.roll();
System.out.printf("The random number is %s (%d).%n", num, num.getValue());
}
}
Related
My program asks the user for a number and then validates if the number is either within the range of two randomly generated numbers or outside the range. The variable num is supposed to be the user's guess, but it keeps equating to 0. I'm uncertain if it has to do with the num = 0 in main, which is there because I get a "variable might not of been initialized" error if the = 0 is not there.
Code:
public static int getValidGuess(Scanner get)
{
int num;
System.out.print("Guess a number: --> ");
num = get.nextInt();
return num;
} // getValidGuess end
public static boolean displayGuessResults(int start, int end, int num)
{
boolean result;
Random gen = new Random();
int n1 = gen.nextInt(99) + 1;
int n2 = gen.nextInt(99) + 1;
if (n1 < n2){
start = n1;
end = n2;
} //if end
else
{
start = n2;
end = n1;
} //else end
System.out.println("\nThe 2 random numbers are " + start + " and " + end);
System.out.println("User Guess is " + num);
if(num >= start && num <= end){
result = true;
System.out.println("Good Guess!");
}
else if(num < start || num > end){
result = false;
System.out.println("Outside Range.");
}
else{
result = false;
}
return result;
} // displayGuessResults end
public static void main(String[] args) {
// start code here
int start = 0, end = 0, num = 0;
Scanner scan = new Scanner(System.in);
String doAgain = "Yes";
while (doAgain.equalsIgnoreCase("YES")) {
// call method
getValidGuess(scan);
displayGuessResults(start, end, num);
System.out.print("\nEnter YES to repeat --> ");
doAgain = scan.next();
} //end while loop
} //main end
Variables in different functions aren't magically the same just because they have the same name. If you want to be able to share variables without passing them as parameters or return values, then you need to declare them in the class instead.
Specifically, here's your two choices. Choice 1 (recommended): change getValidGuess(scan); to num = getValidGuess(scan);. Choice 2: put public static int num = 0; right in your class, outside all of your functions, and remove the declarations of num from all of your functions.
I am currently having an issue with a problem where my java index is out of bounds. The specific error is inside my binaryToDecimal method and is Index 32 out of bounds for length 32. I have tried to reorganize my code as in declaring the int binaryVal[] = new int[32]; as a global variable to fix the error but it does not work. How do I fix this issue?
import java.util.Scanner;
public class NumberConverter {
public static Scanner input = new Scanner(System.in);
static boolean success;
static String originalNum;
static int value = 0;
static int choice = 0;
static int intNum = 0;
static int remainder;
static char [] valueBinaryArray;
public static void main(String[] args) {
// TODO Auto-generated method stub
greeting();
getOriginalNumber();
getOutputType();
//checkValidInput();
if (value == 2 && choice == 3) {
decimalToHex();
}
else if (value == 3 && choice == 2) {
hexToDecimal();
}
else if (value == 2 && choice == 1) {
decimalToBinary();
}
else if (value == 1 && choice == 2) {
binaryToDecimal();
}
}
public static void greeting() {
System.out.println("Hello and welcome to the number systems converter");
System.out.println("Below you will be givin options as to what numbers you'd like to convert");
System.out.println("");
}
public static String getOriginalNumber() {
System.out.println("Enter a number:");
originalNum = input.next();
System.out.println("What type of number is this?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
value = input.nextInt();
return originalNum;
}
public static void getOutputType() {
System.out.println("Which number system would you like to convert to?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
choice = input.nextInt();
}
public static void checkValidInput() {
}
public static void decimalToHex() {
int intNum = Integer.valueOf(originalNum);
String str2 = "";
char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while (choice > 0) {
remainder = intNum % 16;
str2 = hex[remainder] + str2;
intNum = intNum/16;
}
}
public static void hexToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
String hexVal = "";
int digit;
while (choice > 0) {
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
}
for (counter = hexVal.length()-1; counter>=0; counter--)
System.out.print(hexVal.charAt(counter));
}
public static void decimalToBinary() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.println(binaryVal[i]);
}
}
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
}
If you have an array with 32 items the first one is index 0 and the last one is index 31. Trying to access the item at position 32 goes out of the range of the array which is why you get an array index out of bounds exception.
To see the output I would suggest maybe make the array 33 big instead of 32. It's not a proper fix but you should be able to see what it is doing.
If it still goes out of bounds I'd have a closer look at your while loop end condition.
so what is causing your error is your condition in your for statement. Currently, you are just checking if choice >= 0 the problem with this check is that it allows the for statement to go beyond the length of the array you have specified (32). In order to fix this error, you simply need to add another check to make sure the for loop cannot go beyond the length of the array you have specified. This can be done by adding this statement into your for loop: counter < binaryVal.length. This should prevent the for loop from going beyond the length of your array and you shouldn't run into any errors. Your final code for your binaryToDecimal method should look like this:
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0 && counter < binaryVal.length) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
I am writing a Craps dice program for Java. I can't figure out how to pass the Scanner "playerName" from the main method into the playgame method and rolldice method. I want to be able to have the program print the player name in both of these methods. (Example "Jake rolled a 4 and 5 for a total of 9" instead of "Player rolled a 4 and 5 for a total of 9". I also get the warning Resouce Leak: 'sc' is never closed. I am new to the programming scene so if you could explain in simple terms i would greatly appreciate it. Any suggestions to improve the program are also welcome.
import java.util.Scanner;
import java.util.Random;
public class crapsgame
{
//generates random number to be used in method rollDice
private Random randomNumbers = new Random();
//enumeration of constants that represent game status
private enum Status {WIN, LOSE, CONTINUE};
//represents possible outcomes of rolling the dice
private final static int two = 2;
private final static int three = 3;
private final static int seven = 7;
private final static int eleven = 11;
private final static int twelve = 12;
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter a player name: ");
String playerName = sc.nextLine();
crapsgame game = new crapsgame(); //created object of class "crapsgame"
game.playgame(); //tells crapsgame object "game" to invoke"playgame" method
}
//method to play game
public void playgame()
{
int currentPoint = 0; //holds point value for current roll
Status gameResult; //contains one of enumeration values
int sumofDice = rollDice(); //sum after first roll
//determines if won, lost, or continue
switch (sumofDice)
{
case seven:
case eleven:
gameResult = Status.WIN;
break;
case two:
case three:
case twelve:
gameResult = Status.LOSE;
break;
//game continues if above conditions are not met
default:
gameResult = Status.CONTINUE;
currentPoint = sumofDice;
System.out.printf("Point is %d\n", currentPoint);
}
while (gameResult == Status.CONTINUE)
{
sumofDice = rollDice();
if (sumofDice == currentPoint)
gameResult = Status.WIN;
else
if (sumofDice == seven)
gameResult = Status.LOSE;
}
if (gameResult == Status.WIN)
System.out.println("Player wins");
else
System.out.println ("Player loses");
}
public int rollDice()
{
//choose a random number from 1-6
int firstroll = 1 + randomNumbers.nextInt(6);
int secondroll = 1 + randomNumbers.nextInt(6);
int sum = firstroll + secondroll;
System.out.printf("Player rolled %d and %d for a total of %d\n", firstroll, secondroll, sum);
return sum;
}
}
After you get the name from the user you have to pass playerName as a String argument to any function where you want to use it.
I also changed your class name to camel case.
import java.util.Scanner;
import java.util.Random;
public class CrapsGame {
//generates random number to be used in method rollDice
private Random randomNumbers = new Random();
//enumeration of constants that represent game status
private enum Status {WIN, LOSE, CONTINUE};
//represents possible outcomes of rolling the dice
private final static int two = 2;
private final static int three = 3;
private final static int seven = 7;
private final static int eleven = 11;
private final static int twelve = 12;
public static void main (String[]args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter a player name: ");
String playerName = sc.nextLine();
CrapsGame game = new CrapsGame(); //created object of class "CrapsGame"
game.playgame(playerName); //tells CrapsGame object "game" to invoke"playgame" method
}
//method to play game
public void playgame(String playerName) {
int currentPoint = 0; //holds point value for current roll
Status gameResult; //contains one of enumeration values
int sumofDice = rollDice(playerName); //sum after first roll
//determines if won, lost, or continue
switch (sumofDice)
{
case seven:
case eleven:
gameResult = Status.WIN;
break;
case two:
case three:
case twelve:
gameResult = Status.LOSE;
break;
//game continues if above conditions are not met
default:
gameResult = Status.CONTINUE;
currentPoint = sumofDice;
System.out.printf("Point is %d\n", currentPoint);
}
while (gameResult == Status.CONTINUE)
{
sumofDice = rollDice(playerName);
if (sumofDice == currentPoint)
gameResult = Status.WIN;
else if (sumofDice == seven)
gameResult = Status.LOSE;
}
if (gameResult == Status.WIN)
System.out.println(playerName + " wins");
else
System.out.println (playerName + " loses");
}
public int rollDice(String playerName)
{
//choose a random number from 1-6
int firstroll = 1 + randomNumbers.nextInt(6);
int secondroll = 1 + randomNumbers.nextInt(6);
int sum = firstroll + secondroll;
System.out.printf("%s rolled %d and %d for a total of %d\n", playerName, firstroll, secondroll, sum);
return sum;
}
}
In order to pass parameters into a method they need to be declared in the method declaration
public void playGame(String playerName) {
...
}
You then call into the method in the following way
String playerName = sc.nextLine();
playGame(playerName);
As far as the warning you're receiving, you need to close the scanner when you're done using it, i.e
sc.close();
I hope that helps and welcome to programming!
So I have this assignment for class about doing something that implemented methods. I made this really simple program to give you a lucky number of the day. But for some reason, I couldn't get it to run properly more than twice.
The version I'm posting doesn't contain the loop, but I tried about 10 different ways and it just wouldn't work. Either it would keep spitting out numbers endlessly, or it would print out the welcome lines again instead of just the "would you like another number y/n" line. If someone could just help me figured out how I should have organized it so that the loop only displays this line:
Would you like to receive another number? y/n
and then if the user decides yes, the intro method runs again and that line displays again until uses presses "n"
here's the code:
import java.util.Scanner;
import java.math.BigInteger;
import java.util.Random;
public class MinOppgave2 {
public static void main(String[] args) {
menu();
}
public static void menu(){
//intro text
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
intro();
Scanner input = new Scanner(System.in);
System.out.println("Would you like to receive another number? y/n");
String txtinput = input.nextLine();
if (txtinput.equalsIgnoreCase("y")){
intro();
}
else if (txtinput.equalsIgnoreCase("n")){
System.out.println("That's all for now, have a nice day!");
}
System.out.println("That's all for now, have a nice day!");
}
public static void intro(){
// user choice
Scanner input = new Scanner(System.in);
System.out.println("Please choose between: even odd or prime");
String text1 = input.nextLine();
//if/else user choice arguments
if (text1.equalsIgnoreCase("even"))
Evennum();
else if (text1.equalsIgnoreCase("odd"))
Oddnum();
else if (text1.equalsIgnoreCase("prime"))
Prime();
else
menu();
}
public static void Evennum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isEven(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Oddnum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isOdd(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Prime(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
// prime checker
private static boolean isPrime(int numin){
if (numin <= 3 || numin % 2 == 0)
return numin == 2 || numin == 3;
int divisor = 3;
while ((divisor <= Math.sqrt(numin)) && (numin % divisor != 0))
divisor += 2;
//true/false prime answer
return numin % divisor != 0;
}
private static boolean isEven(int numin){
//math argument for even number
return (numin % 2) == 0;
}
private static boolean isOdd(int numin){
//math argument for even number
return (numin % 2) == 1;
}
}
Wrong recursion on the wrong place...
Try this:
public static void intro() {
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
}
public static String takeInput() {
Scanner input = new Scanner(System.in);
return input.nextLine();
}
public static boolean pickNumber() {
System.out.println("Would you like to receive another number? y/n");
if (!takeInput().equalsIgnoreCase("y")) {
System.out.println("That's all for now, have a nice day!");
return false;
}
System.out.println("Please choose between: even odd or prime");
String chosen = takeInput();
//if/else user choice arguments
if (chosen.equalsIgnoreCase("even"))
Evennum();
else
if (chosen.equalsIgnoreCase("odd"))
Oddnum();
else
if (chosen.equalsIgnoreCase("prime"))
Prime();
return true;
}
public static void main(String[] args) {
intro();
while (pickNumber())
;
}
I am making a lottery application in Java. My problem is that I think everything is in place and it (the IDE) is telling me that "int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;" needs to be static. So I change it to a static int and then I have to change it again in my class. Problem is when I finally run it I get all 0's for my random lottery data. Please help me find the errors in my ways. Total newb here and I've been looking online here but I want to try to figure it out without just copying code somewhere.
Eck_LotteryClass
import java.util.Random;
public class Eck_LotteryClass {
//instance field
private int lotteryNumbers [];
//Create random lottery numbers method array
public int [] getRandomNumbers(){
lotteryNumbers = new int [5];
Random r = new Random();
for(int i = 0; i < 5; i++)
lotteryNumbers[i] = r.nextInt(10);
return lotteryNumbers;
}
public int compareNumbers(int[] usersNumbers) {
int matchedNums = 0;
if (usersNumbers.length == lotteryNumbers.length) {
for (int i = 0; i < lotteryNumbers.length; i++) {
if (usersNumbers[i] == lotteryNumbers[i]) {
matchedNums ++;
}
}
}
return matchedNums;}
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
}
Eck_LotteryTester
import java.util.Scanner;
import java.util.Arrays;
public class Eck_LotteryTester{
public static void main(String[] args) {
Eck_LotteryClass lottery = new Eck_LotteryClass();
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
System.out.println("The Pennsylvania Lottery\n");
System.out.println("There are " + lotteryNumbersCount
+ " numbers in my lottery, they are 0 through 9. "
+ "See if you can win big CASH prizes!!!\n");
// Asks the user to enter five numbers.
Scanner keyboard = new Scanner(System.in);
int numbers[] = new int[lotteryNumbersCount];
for (int index = 0; index < numbers.length; index++) {
System.out.print(String.format("Enter Number %d: ", index + 1));
numbers[index] = keyboard.nextInt();
}
// Display the number of digits that match the randomly generated
// lottery numbers.
int match = lottery.compareNumbers(numbers);
if (match == lotteryNumbersCount) {
// If all of the digits match, display a message proclaiming the
// user a grand prize winner.
System.out.println("\nYOU WIN, GO SEE D. LEETE FOR YOUR GRAND PRIZE!!!");
} else {
System.out.println("\nThe winning numbers are " + Arrays.toString(Eck_LotteryClass.getLotteryNumbers()) +
"\nYou matched " + match + " number(s).");
}
}
}
Change
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
to
int lotteryNumbersCount = lottery .getLotteryNumbers().length;
and you won't have to change the methods signature to static. Also you'll be talking about the same variable.
Also change
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
to
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return getRandomNumbers();
}
So the array gets initialized. And changing the signature of
public int [] getRandomNumbers
to
private int [] getRandomNumbers
wouldn't hurt
package New_list;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tWelcome to Harsh Lottery System.\n");
Random random = new Random();
int lottery_win_1 = random.nextInt(10);
// Print Lottery winning number...1 :P
// System.out.println(lottery_win_1 + "\n");
int lottery_win_2 = random.nextInt(10);
// Print Lottery winning number...2 :P
// System.out.println(lottery_win_2 + "\n");
boolean loop = true;
while(loop){
System.out.println("\t\t\tEnter your 2 Digit Lottery number.\n");
scan = new Scanner(System.in);
int lottery_no = scan.nextInt();
if ((lottery_no >= 0) && (lottery_no <= 99)) {
int lottery_no_1, lottery_no_2;
if (lottery_no > 9) {
lottery_no_1 = lottery_no / 10;
lottery_no_2 = lottery_no % 10;
} else {
lottery_no_1 = 0;
lottery_no_2 = lottery_no;
}
if ((lottery_win_1 == lottery_no_1)
&& (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation you win lottery,and you win $10000.\n");
} else if ((lottery_win_1 == lottery_no_2)
&& (lottery_win_2 == lottery_no_1)) {
System.out
.println("\t\t\tCongratulation your inverse no is lottery winer number so that you win $4000.\n");
} else if ((lottery_win_1 == lottery_no_1)
|| (lottery_win_1 == lottery_no_2)
|| (lottery_win_2 == lottery_no_1)
|| (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation your one digit from your lotter number match to the lottery winner.so you win $1000.\n");
} else {
System.out.println("\t\t\tSorry,Please try again\n");
System.out.println("\t\t\tDo you want to try again\n\t\t\tPress 1 for Continue\n\t\t\tPress 2 for exit\n");
int ch = scan.nextInt();
switch(ch){
case 1: System.out.println("\t\t\tOk...Try again\n");
break;
case 2: System.out.println("\t\t\tBbye... See you later\n");
loop = false;
break;
}
}
} else {
System.out.println("\t\t\tSorry,Please choose 2 digit number\n");
}
}
}
}