Issue with ending a while loop - java

I am trying to make the program end when total reaches 10, but for some reason my while loop continues counting when it reaches 10. I have the int percent to find the percent once 10 questions are answered.
import java.util.*;
class CAI {
private static Scanner input;
public static void main(String[] arguments) {
menu();// calls menu method
compute();// calls compute method
}
public static void menu() {// method that displays menu
System.out.println(" CAI MENU ");
System.out.println("\n)");
System.out
.println("\n1) DIFFICULTY 1\n2) DIFFICULTY 2\n3) DIFFICULTY 3\n4) DIFFICULTY 4");
}
public static int[] Blop() {
Random rand = new Random();
int arr[] = new int[8];
arr[0] = rand.nextInt(9);
arr[1] = rand.nextInt(9);
arr[2] = rand.nextInt(99);
arr[3] = rand.nextInt(99);
arr[4] = rand.nextInt(999);
arr[5] = rand.nextInt(999);
arr[6] = rand.nextInt(9999);
arr[7] = rand.nextInt(9999);
return arr;
}
public static void compute() {
int difficulty;
input = new Scanner(System.in);
System.out.println("Enter an option: ");
difficulty = input.nextInt();
int total = 0;
int percent = 0;
while (total <= 10) {
if (difficulty == 1) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[0] + " times "
+ num[1] + " ? :");
total++;
System.out.print(total);
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[0] * num[1])) {
System.out.print(Correct);
percent++;
} else {
System.out.print(Wrong);
}
} while (ans != (num[0] * num[1]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
}
if (difficulty == 2) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[2] + " times "
+ num[3] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[2] * num[3])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[2] * num[3]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 3) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[4] + " times "
+ num[5] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[4] * num[5])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[4] * num[5]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 4) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[6] + " times "
+ num[7] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[6] * num[7])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[6] * num[7]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
System.out.print(100 / 10 * percent);
}
}

Your while loop is declared:
"while total is less than or equal to ten"
which means it will run once again at 10.
just make it while total <10
edit: you also don't increment total anywhere.
total++;
will do it.
edit: it appears you do. sorry the code is hard to read on a phone.

There could be multiple reasons for this happening. One such reason is that if the variable difficulty does not equal one(this variable is nowhere to be found in your code also), then total will never be incremented, and as a result the first while loop will last forever. Because you have not shared all of your code, it could also be that ans != (num[0] * num[1] is never true, and as a result, the innermost do/while loop is executed forever. If you post the rest of your code, we will be able to assist you more.
EDIT: OK, thanks. It looks like your problem is due to the fact that while the user continues to get the question wrong, they cannot escape the inner while loop, therefore not being able to escape the outer while loop. The solution to that is easy, simply changing while (ans != (num[4] * num[5])); to ans != (num[0] * num[1]) && total < 10, thereby giving the code a way to escape while the user is getting the question wrong.

Related

ArrayList If Loop not working properly: JAVA

I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
return numShuffles;
}

Guessing number using lower,higher,correct options in java

I'm trying to write a java code in java that has following output.
---JGRASP exez: java Guess
Is the number 50? H
Ia the number 75? L
Is the number 62? L
Is the number 56? L
Is the number 53? L
Is the number 51? C
It took me 6 guesses!
---JGRASP: operation complete.
As you see it always cuts range in half.I spent hours trying to figure it out without results.I would really appreciate if you could at least give a hint.Here's my unsuccessful attempt to write the code.
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[]args)
{
int num1 = 0,num2 = 100,guesses = 0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Is the number " + <?> + "? "); //have no idea
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}
public static void main(String[]args)
{
Random randomNumber = new Random();
int num1 = 0,num2 = 100,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=randomNumber.nextInt(num2-num1) + num1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
Try this, what it does is that, while the answer is not correct, It will take in num1(the min value for the guess) and num2(the max value for the guess) and find their average. If the number is higher than the latest guess, we set the lower bound to the latest guess, if it's lower, we set the upper bound to the latest guess.
import java.util.Scanner;
public class GuessNumber{
public static void main(String[]args)
{
int num1 = 0,num2 = 101,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=(num1+num2) /2 > 0? (num1+num2) /2:1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guesses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}

Incompatible Types in If Statement

I am getting an incompatible types error message in my if statement. The variables "answer" and "input2" are both integers so I am not sure how the two are incompatible. Any help or insight would be much appreciated!
public static void addingGame()
{
System.out.print("\n");
System.out.println("********* Part 2: Adding Numbers **********");
System.out.print("\n");
Scanner inputReader = new Scanner(System.in);
System.out.print("Would you like to add some numbers?(y/n)");
String input = inputReader.next();
while (!input.equals("y") && !input.equals("n"))
{
System.out.print("I need a y/n: ");
input = inputReader.next();
}
while (input.equals("y"))
{
Random numberGenerator = new Random();
int randomNumber1 = numberGenerator.nextInt(10);
int randomNumber2 = numberGenerator.nextInt(10);
int answer = ((randomNumber1) + (randomNumber2));
System.out.print( randomNumber1 + " + " + randomNumber2 + " =: ");
int input2 = inputReader.nextInt();
if (answer = input2)
{
System.out.print("Right! " + answer + " is the answer.");
}
else
{
System.out.print("Sorry, " + answer + " is the answer.");
}
System.out.print("Would you like to play again?(y/n)");
input = inputReader.next();
while (!input.equals("y") && !input.equals("n"))
{
System.out.print("Sorry - I need a y/n: ");
input = inputReader.next();
}
}
System.out.print("\n");
System.out.print("Thanks - Let's move on to Part 3...");
You're using the assignment operator = when you wanted to compare the values (==). Change
if (answer = input2)
to
if (answer == input2)
The error came from the fact that the result of the assignment is still an int, where as the if condition expects a boolean, which == provides.

Storing user input to an array java

I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!

How to assign a random number a string value in my program

as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}

Categories