Loop Through 3 Slot Machines Indefinitely Java Program

  • I'm still pretty new to Java, so I'm having some issues working out this slot machine program. After you run the program the first time and calculate the rewards (say, you bet $20 and win $40, so your new sum's $120), it's supposed to loop back around and prompt 'how much would you like to bet?'
  • In particular, this MOOC covers key Java programming language features that control the flow of execution through an app (such as Java’s various looping constructs and conditional statements), enable access to structured data (such as Java's built-in arrays and common classes in the Java Collections Framework, such as ArrayList and HashMap.

So you’ve just started learning Java, you’ve built your first Hello World program, and you’re feeling like a pro. But if you want your programs to do more and be more, you have to learn how to use loops.

There are three kinds of loop statements in Java, each with their own benefits – the while loop, the do-while loop, and the for loop. Loop mechanisms are useful for repeatedly executing blocks of code while a boolean condition remains true, a process that has a vast amount of applications for all types of software programming.

To understand the distinct uses of each loop statement, let’s take a look at the simple while loop. If you want a more in-depth, beginner friendly guide to learning Java, check out this tutorial for Java programming basics.

The slot machine then displays a set of random images. If two or more of the images match, the user wins an amount of money that the slot machine dispenses back to the user. Create a class that simulates a slot machine. When the program runs, it should do the following: 1. Asks the user to enter the amount of money he or she wants to enter into.

Syntax of the While Loop

The syntax of a while loop is as follows:

The while statement will evaluate the boolean expression within the parentheses, and continue to execute the statement(s) within the curly braces as long as the expression is true.

This is the most important characteristic to note. The entirety of the loop body will be skipped over if the expression evaluated in the beginning is not true.

Keep this in mind for later when we examine the do-while loop. For now, let’s check out the while loop in action.

Example of a While loop

Java

Let’s say you want to create a program that will count from 1 to 10, using a while loop.

This is what your program will look like, and this is what it will return:

What’s Going on Here?

Before we even open the loop, we have to set a condition for its boolean to evaluate. Because we want to count to 10, we create an int – named num in this example – and set its initial value to 0. We then have the program print the string, “Let’s count to 10!”

From here, we open our while loop using the syntax we talked about before. Our goal is to increase the value of num to 10, one number at a time, before closing the loop. To do this, we set our boolean expression to num < 10. As long as the value of num is less than 10, it will continue executing the statements within the loop.

Those statements are num = num + 1, and a string that prints the word “Number:” followed by the current value of num after each execution.

Loop Through 3 Slot Machines Indefinitely Java Programming

What the program is doing is repeatedly checking the current value of num, adding 1, and printing its new value, before starting the process over again, and finally ending once the value of num is 10.

Once the loop is closed, it moves on to the next statement, which is a string that reads, “We have counted to 10! Hurray!” The program moves onto this next line because the boolean expression in the while loop above is no longer true, and so the while loop has closed.

Some While Loops Never Run

It’s possible for the loop body to never run at all, if the conditions are so that the boolean was either never true, or instantly untrue.

For instance, if the initial value of num is 0 and our boolean expression is num > 10, instead of num < 10, it is already false from the start, because 0 will never be greater than 10.

Our while loop will evalute the boolean expression, num > 10, find that it is untrue, and print:

The Do-While Loop

The syntax of a do-while loop is very similar to the while loop, with one significant difference – the boolean expression is located at the end of the loop, rather than at the beginning. This means the statements in the loop body will execute one time, before the boolean expression is evaluated.

What this returns is:

The main noticeable difference between what our first while loop returned and what this do-while loop returns is that our do-while loop counts from 0. This is because our do-while statement prints the initial value of num once before adding to it, evaluating the boolean, and then starting over.

This is also why it stops at 9, instead of 10, like our first while loop – once the value of num is 9 at the beginning of the loop, the statement num = num + 1 makes it 10, rendering the boolean expression num < 10 untrue, thus closing the loop before it can print the next value.

You can read a more in-depth guide on how do-while loops work here.

Getting Stuck in an Infinite Loop

One of the most common errors you can run into working with while loops is the dreaded infinite loop. You risk getting trapped in an infinite while loop if the statements within the loop body never render the boolean eventually untrue. Let’s return to our first example.

Before, our statement num = num + 1 continually increased the value of num until it was no longer less than 10, rendering our boolean expression num < 10 untrue, and closing the loop – great success!

However, what if we had accidentally written num = num – 1 within the while loop?

This would continue subtracting 1 from num, down into the negative numbers, keeping its value less than 10, forever. This is an infinite loop because our boolean will always remain true, meaning our program will continue to run it with no end in sight, unless we fix it.

This has been a basic tutorial on while loops in Java to help you get started. If you’re starting to envision yourself in a long and fruitful career coding in Java, check out this guide to Java-based interviews and their most common questions. If you still have a lot to learn, dive in with the ultimate Java tutorial for beginners.

The following java for-loop exercises have been collected from various internet sources such as programmr.com and codewars. Go to my tutoring page if you need more help and would like to talk to a tutor.

User input does not work with the embedded compiler (paiza) below. That is why you see the problems being worded and setup slightly differently than on the rest of the page.

Happy Coding!

Exercise 1:

Determine and print the number of times the character ‘a’ appears in the input entered by the user.

Exercise 2:

Write a program that will print a box of #’s taking from user the height and width values.

Exercise 3

Write a program to find the sum of 5 integers.

Exercise 4

Write a java program to calculate the factorial value of given number. Factorial x –> x * x-1 * x-2…x*1

Example: factorial 4 = 4 * 3 * 2 * 1 = 24

Exercise 5

Suppose we have a database composed of two fields or columns (arrays), the first field is for the username (user[]) and the other one is for the password(pass[]) .

This is how it looks like:

user[0] = “Hassan” ;

user[1] =”Idris”;

user[2]=”Trevor” ;

And their passwords correspond with their indexes.

pass[0] = “homecomingking”;

pass[1] = “turnupcharlie”;

pass[2] = “afraidofthedark”;

Then if one of them had successfully login, the output should be:

Enter username: Hassan

Enter password: homecomingking

Hello Hassan!

But if not, “Incorrect Login!”

You can ignore case for the username but not for the password.

Exercise 6

You have to design the code such that the user has only three tries to guess the correct pin of the account. You set the pin as a constant with a final attribute. When correct display “Correct, welcome back.” When incorrect display “Incorrect, try again.”. When ran out of tries display “Sorry but you have been locked out.”

Exercise 7

Write a program that prompts user for a word and prints “Yes” if it is a palindrome and “No” if it is not.

Exercise 8 (Advanced)

This is a code wars kata. click here to train on “Abbreviate a Two Word Name” on code wars.

Write a function to convert a name into initials. You can assume the program takes in two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Exercise 9

This is a code wars kata. click here to train on “Grasshopper – Summation” on code wars.

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

Exercise 10

This is a code wars kata. click here to train on “Sentence Smash” on code wars.

Write a method smash that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. Be careful, there shouldn’t be a space at the beginning or the end of the sentence!