Slot Machine Java Code While/for Loops
Broadly classifying, there are three types of loops in Java programming which are: 1. While loop makes it quite easy. Let's first look at the syntax of while loop. On this post, let’s take a look at how beginners of Java programming can make a simple, yet fully functional slot machine. Slot machines have been around for a long time, but its entertainment value doesn’t seem to fade one bit. Casinos are a shady business, but I'm even more suspicious of a slot machine that offers me a random prize without displaying the result of the spin. Infrastructure I don't recommend developing a habit of relying on non-standard libraries that don't do very much. Change your initial cont = 'n' to cont = 'y', and have the while loop check if (cont.equals ('y')). This is a quick fix, there are many changes that could be made for efficiency and to keep up with standards, but I won't go into detail. The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
- Slot Machine Java Code While/for Loops C++
- Slot Machine Java Code While/for Loops Download
- Slot Machine Java Code While/for Loops Tutorial
- Simple Slot Machine Java Code
How do you write the code using Scanner class to set up a menu (i.e 1 for something, 2 for something, and so on.) Then have the user to choose.
Thanks
- 5 Contributors
- forum6 Replies
- 25,086 Views
- 6 Years Discussion Span
- commentLatest PostLatest Post by fairy1992224
Recommended Answers
Something along these lines:
Jump to PostHow do you write the code that allows you to go back to the menu after choosing an option?
Hi
You can make it simple an add a new method like in this example below that is based on the class above. I have chanced the name of the …
Jump to PostAll 6 Replies
This section under construction.
Although the TOY machine language contains only 16 different instructiontypes, it is possible to perform a variety of interestingcomputations. In fact,any computation that can be done in the Java programming language on your PCcan also be done in TOY (provided you give TOY enough main memory and time).This may come as quite a surprising fact; we will justify it later inChapter 8. Below, we describe each of the instructions in the TOY language.
Memory-register transfer (opcodes 8 and 9).
To transfer data between registers and main memory, we use theload (opcode 8) and store (opcode 9) instructions.These operations are convenient because it is not possibleto perform arithmetic operations directly on the contents ofmain memory. Instead, the data must be first transferred toregisters. There are also circumstances where it is not possibleto maintain all of our program's variables simultaneously inregisters, e.g., if we need to store more than 16 values.We overcome the 16 register limitation bystoring variables in main memory, and transferring them backand forth to registers using the load and store instructions.Arithmetic operations (opcodes 1 and 2).
The add (opcode 1) and subtract (opcode 2)perform the conventional arithmetic operations.In TOY, all arithmetic operations involve 16 bit two's complementintegers, as described in Section 5.1.- Addition.Program add.toy treatsmemory addresses 00 and 01 as storing theinput values for variables RA and RB.It then calculates the sum of the two values and puts theresult temporarily in register C.Finally, it transfers the contents of register C back to memory,and stores it at memory address 02.It is important to note that memory locations 00 through 02 never get executed in this program;they are treated as data.
Upon termination of this program, register C contains the value000D, the hexadecimal equivalent of the decimal integer 13.(If you computed the result 0013, start getting adjustedto working with hexadecimal integers.)
What happens if the result ofthe arithmetic operations is too large to fit into a 16 bitregister? Such overflow is handled by disregarding everythingexcept the rightmost 4 hex digits.For example, the result of adding EFFF and 1005 is 0004,since EFFF + 1005 = 10004 in hex and we discard the leadingdigit. This is the way addition works in Java, except that thereare 32 bits in an int instead of the 16 in a TOY word.
- Subtraction.Analogously, the programsubtract.toycomputes 0005 - 0008 = FFFD.The answer FFFD is the hexadecimal equivalent ofdecimal integer -3 using two's complement integers.(Review Section 5.1 for a description of two's complementnotation.)
Standard input and standard output.
The load and store instructions are also used to accessstandard input and standard output. The distinguished memory address FF is intercepted by a TOY hardware interrupt:instead of loading or storing information in memory locationFF, the data is received from the keyboard or is sentto the screen.- Sum two integers.Program stdin.toyreads two integers from standard input, and writes their sum tostandard output.
When the program is executed, it pauses until the user types intwo integers. As usual, the integers are specified as 4 hexadecimaldigits. Then it computes their sum, and prints it to the screen.
- Fibonacci numbers.Program fibonacci.toy prints to standardoutput the sequence of Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, D, etc.
- Sum of sequence of integers.Program sum.toy reads in a sequence of integers from standard input and prints out their sum. It stopsupon reading in the integer 0000.It illustrates a program thatcan process more information than fits in TOY memory.
Implications of standard input and output.The standard input and standard output facilities of TOY have a profoundeffect on what the TOY machine is capable of. An obvious featureis to get information in and out of the machine.This information can be data, but it can also be instructions!Booting a computer is copying a sequence of stored instructions(e.g., the operating system) into the machine.The TOY machine has only a limited memory (256 words plus a few registers). Nevertheless, it is possible to process more informationthan this.Another advantage of standard input is that it offers a crude form ofuser interaction.
Flow control (opcodes C and D).
So far, we have seen how to use TOY as a calculator. Branchstatements enable us to harness the true power of TOY, much likewhile loops and if-else conditionals enabled usto harness the power of Java.The value of the program counter controls which statement theTOY machine will execute next. Typically, the program counter is incrementedby one at each time step. This causes the instructions to be executed in order,one after the other.The branch if zero (opcode C) and branch if positive(opcode D) enable us to directly change the program counter,thereby altering the flow of control of our programs.- Powers of two.Program powers2.toy prints out the positive powers of 2, using a branch if positive statement.
- Infinite loop.The ability to change the flow-of-control of a program introducesthe possiblity for infinite loops, as in infinite_loop.toy.
- Multiplication.Conspicuously absent from the TOY instruction set is a multiply instruction.To achieve the same effect in software, we describe and implementan algorithm to multiply two integers.The brute force way tocompute c = a * b is to set c = 0,and then add a to c, b times.This suggests having aloop that repeats b times. We accomplish this by makinga counter variable i that we initialize to b,and then decrement it by one until it reaches 0. We use thebranch if positive instruction to detect this event. Theprogram multiply.toy loadstwo integers from memory locations 0A and 0Binto registers A and B, multiplies them together and putsthe result in register C, then writes the result back tomemory location 0C.
The astute reader might notice that our algorithm suffers froma serious performance flaw. The brute force algorithmis inefficient if the values are large. The loopiterates b times, and since b is a 16-bit integer,it can be as large as 32,767. This issue would be much more pronouncedon a 64-bit machine where the loop might requirea mind-boggling 9,223,372,036,854,775,807 iterations! Fortunately, we can incorporate better algorithmic ideas (as we do below)to rescue this otherwise hopeless task.
TOY idioms.There are several common idioms or pseudo-instructionsin TOY that can be used for common programming tasks.Many of these tricks rely on the fact that register 0always stores the value 0000
- Register-to-register transfer.Suppose you want to make register 2 have the same value asregister 1.There is no built-in instruction to do this.Relying on the fact that register 0 always contains0000, we can use the addition instruction tosum up R0 and R1 and put the result in R2.
- Swap.As a more sophisticated example, suppose we want to swap thecontents of two registers RA and RB....
- No-op.In a structured programming language like Java (withfor and while loops), inserting extra codeis easy.In an unstructured language like TOY (where there areline numbers and goto statements), you must be careful aboutinserting code. A branch statement hardwires in the memory addressto jump to; if you insert code, the line numbers ofyour program may change.To avoid some of this awkwardness, machine language programmersoften find it convenient to fill in the program with'useless' statements to act as placeholders.Such statements are called no-ops because they performno operation.The instruction 1000 is ideal forthis purpose since register 0 is always 0anyway. (The instruction 10xy would also be a no-opfor any values of x and y because register 0 always contains 0, regardless of how you might try to change it.
- Goto.There is no instruction that directly changes the program counter tothe addr. However, it is easy to use the branch if zeroinstruction with register 0 to achieve the same effect. For example,the instruction C0F0 changes the program counter toF0 since register 0 is always 0.
Bit-whacking operators (opcodes 3, 4, 5, and 6).
The bit-whacking operations - bitwise and (opcode 3),bitwise xor (opcode 4),left shift (opcode 5), and right shift (opcode 6) -work just like the analogous ones in Java, exceptusing 16-bit two's complement integers.- Bitwise and and bitwise xor.Bitwise and (opcode 3) and bitwise xor (opcode 4)take two 16 bit integers andand apply the corresponding boolean operator to each of the corresponding16 pairs of bits.For example, if registers 1 and 2 contain the values 00B5 and00E3, then the instruction 3312 assigns thevalue 00A1 to register 3.To see why, consider the binary representationof registers 1 and 2, and take the bitwise andof each corresponding bit.
- Left shift (opcode 5) shifts the bits a certainnumber of places to the left, padding 0s on the right.For example, if register 2 has the value 00B5and register 3 has the value 0002, thenthe instruction 5423 assigns the value 02D4 to register 4.To see why, look at the binary representation.
Note that left shifting by one bit is equivalent to multiplicationby 2; left shifting by i bits is equivalent to multiplyingby 2i.
- Right shift (opcode 6) is similar, but the bits getshifted to the right. Leading 0s or 1s are padded on theleft, according to the sign bit (the leftmost bit).For example, if register 2 has the value 00B5and register 3 has the value 0002, thenthe instruction 6423 assigns the value 002D to register 4.To see why, look at the binary representation.
The value is register 2 is nonnegative so 0s are padded on the left.If, instead, register 2 has the value FF4B, thenthe result of the right shifting is FFD3. In this casethe value in register 2 is negative so 1's are paddedon the left.
Note that right shifting an integer by 1 bit is equivalent to dividing the integer by 2 and throwing away the remainder.This is true regardless of the sign of the original integer.In general, right shifting an integer by i bits is equivalentto dividing it by 2i and rounding down.(Note that this does not exactly agree with integer division in Javaby the corresponding power of two when the numerand is negative,e.g., -181/4 = -45.)This type of shifting is called an arithmetic shift ora signed shift: it preserves the sign for two's complementintegers.
Efficient multiplication.Using the bitwise operators, we provide an efficientimplementation of multiply.toy.To multiply two 16-bit integers a and b, we let bi denote the ith bit of b.That is,
b = (b15 × 215)+ (b14 × 214)+ ...+ (b1 × 21)+ (b0 × 20) |
By distributivity, we obtain:
a × b= (a × b15 × 215)+ ...+ (a × b1 × 21)+ (a × b0 × 20) |
Thus, to compute a × b, it suffices to add the above 16 terms.Naively, this appears to reduce the problem of performing onemultiplication to 32 multiplication, two for each of the 16 terms.Fortunately, each of these 32 multiplications are of a veryspecial type.Recall that a × 2iis the same as left shifting a by i bits.Second, note that bi is either 0 or 1; thus termi is either a << i or 0.Program multiply-fast.toyloops 16 times. In iteration i it computesthe ith term and adds it to the runningtotal stored in register C.To gain some perspective, recall the standard grade schoolalgorithm for multiplying two decimal integers.The bitwise procedure we just described is really justthe grade school algorithm applied to binary integers.
Load address (opcode 7).
The load address instruction (opcode 7)is the most primitive type ofassignment statement in the TOY language.The code fragment below initializes register A to 30.When using the load address instruction, we often think of the destination register as storing the memory address ofsome piece of data. This is especially useful when dealingwith arrays.In the C programming language,this type of variable is known as a pointer.However, we can also use the load address instruction to storea small constant into a register, instead of using theload instruction. Note that load addressonly permits you to assign 8 bit integers (00 through FF)to a register, even though registers are capable of storing 16 bit integers.
Arrays (opcodes A and B).
Arrays are not directly built into the TOY language, butit is possible to achieve the same functionalityusing the load address (opcode 7), load indirect(opcode A),and store indirect (opcode B) instructions.We illustrate this technique with two examples.First, we will consider a program that reads in a sequence ofintegers and prints them in reverse order. Then, we will consider a more sophisticated application of arrays that performs the classic insertion sort algorithm ona sequence of integers.- Reverse.Program reverse.toy readsa sequence of positive integers from standard input, and stopswhen it encounters the integer 0000.It stores the integers in main memory, starting at address 30.We use the load address instruction to store the address 30.Then, it marches through the elements in reverse order,printing them out to standard input.We use register B to keep track of the number of elements read in.We arrange it so that register 6 contains the memory location ofthe array element that we are currently reading or writing.To write and read an array element, we use the opcodes A and B,respectively.
- Buffer overflow.Program reverse.toy suffers from onecritical flaw.Since the TOY machine has only 256 memory locations,it is not possible to store or reverse a list that containstoo many elements. In the example above, after the programfills up memory locations 30 through FF,it will wrap aroundand start writing into memory locations 00 through 0F.Pretty soon, it will start overwriting the lines of the originalprogram 10 through 20. A devious user could exploit this buffer overflow and input integers in such a way that theintegers from standard input get interpreted as instructions ratherthan data. Viruses are often spread by such buffer overflow attacks.
Program crazy8.toy is a version ofreverse.toy that starts storing the array at memory address 00.Thus, after 16 integers are read in and stored, the program starts overwritingitself. The input below is especially malicious. Entering the 20 integerson standard input enables the user to take control of the machine andhave it print out 8888 in an infinite loop.
Functions (opcodes E and F).
In Java it is quite useful to divide a program up intosmaller functions. We can do the same in TOY.Below is a TOY program that 'calls' a multiply functionwith two arguments and computers their product.Since all of the variables (registers) are global, we needto agree upon a protocol for calling our function.We'll assume that we want to multiply the integers storedin registers A and B, and store their productin register C.Program multiply-function.toythat calls themultiply function twice to compute x × y × z,once to compute x × y, then again to compute(x × y) × z.It uses the jump and link (opcode F) and jump register(opcode E)instructions that are especially designed for this purpose.Instructions 11 and 14store the value of the program counter in register 3before jumping to the function located at F0.This makes it possible to return back to the main program,without hardwiring in the address into the program.Every time the program counter is reset to F0, the oldprogram counter is saved away in register F for future use.Instruction F5 returns from the function by resetting theprogram counter to the value stored in register F.Note also, that the program counter is incrementedbefore the instruction is executed. Thus,during the first function call register F is 16and not 15.
Be very careful about which variables you are using when writingmachine language functions. There is no such thing as a 'local variable.' Had we continued to use register 2 asthe loop counter in the multiplication function, this would haveoverwritten register 2 in the main program, which was being usedto store the quantity b.
Horner's method.We can use the multiplication function toevaluate polynomials: giveninteger coefficientsan, ...,a2,a1,a0 and an integer x,evaluate the polynomialp(x)= an xn+ ...+ a2 x2+ a1 x1+ a0 x0at the integer x.Polynomial evaluation was one raison d'etre forearly machines. It has many applications including studying ballistic motion and converting an integerfrom its decimal representation to hexadecimal.
The brute force algorithm for polynomial evaluationis to sum up the n+1 terms, whereterm i is the product of aiand xi.To compute xi wecould write a power function that multipliesx by itself i-1 times.Horner's method is a clever alternative thatis more efficient and easier to code.The basic idea is to judiciously sequence the way inwhich terms are multiplied.We can rewrite an order 3 polynomialBy distributivity, we obtain:
p(x) = a3 x3+ a2 x2+ a1 x+ a0 = (((a3) x+ a2) x+ a1) x+ a0 |
Similarly, we can rewrite an order 5 polynomial
p(x) = a5 x5+ a4 x4+ a3 x3+ a2 x2+ a1 x+ a0 = (((((a5) x+ a4) x+ a3) x+ a2) x+ a1) x+ a0 |
Using Horner's method, only n multiplications are requiredto evaluate an order n polynomial.Moreover, we can translate the method directly into Java or TOY code. Program horner.toy isthe TOY version. In the TOY version, we call our multiply functionevery time we want to multiply two integers.
Horner's method was published in 19th century byBritish mathematician W. G. Horner,but the algorithm was used by Isaac Newton over a century earlier.
We can use horner.toyto convert a decimal integerto its hexadecimal representation.To convert 76510 to hex, we set the inputx = A, n = 3,a2 = 7,a1 = 6, anda0 = 5.Since all arithmetic is performed in hex, the programcomputes the hexadecimal equivalent of 7 × 102 + 6 × 10 + 5 = 02FD.
Insertion sort.The program insertion-sort.toyreads in a sequence of positive integersfrom standard input and insertion sorts them. The program terminatesupon reading in a nonpositive integer.
Slot Machine Java Code While/for Loops C++
Linked lists.
This code will traverse the linked list starting atmemory location D0, printingout the integer stored in each 'node.'It will print out 0001 0002 0003 0004.Throughout the computation R1 is always 1.Indexed addressing is used in instructionsA304 and A203Register R2 is a pointer - it is thememory address of the next node.Register R3 is a pointer to the memory address immediatelyafter R2.At each iteration of the loop we print the contents ofthe value in memory referenced by R2 and use the value in memory referenced by R3 to determine what memoryaddress R2 will store in the next iteration.For the data given above, register R2 will have thevalues D0, D6, DA, D4,and 00 in that order.This process is repeated until R2 is 0000, i.e.,the end of the linked list. In Java, the keyword nullplays the role of 0000 and is used to terminate linked lists.
Slot Machine Java Code While/for Loops Download
Recursion.You can also do recursion in TOY, but this is rather tricky.
Exercises
Slot Machine Java Code While/for Loops Tutorial
- Write a program powers2.toy that prints out all of the positive powers of 2 to standard output.
- Given an integer x, its Collatz sequence is defined byreplacing it with x/2 if x is even, and 3x + 1 is x is odd,and repeating until x is 1.Write a program collatz.toy thats reads an integer xfrom standard input and prints its Collatz sequence tostandard output.Hint: use right shift to perform integer division by two.
- Write a program sum_1-n.toy that readsin an integer N from standard input and prints out the sum1 + 2 + 3 + ... + N.
- Write a program min3.toy that reads in three integersfrom standard input and print to standard output the smallestone.
- Write a program max3.toy that reads in three integersfrom standard input and print to standard output the largest one.
- Write a program sort3.toy that reads in three integersfrom standard input and print them out to standard output inascending order.
- Write a program chop.toy that readsin an integer N from standard input and prints it out as thesum of powers of 2. For example if N = 012A, thenthe program should print out
since 012A = 0002 + 0008 + 0020 + 0100.
- This question tests the difference between load address, load,and load indirect. For each of the following TOY programs,give the contents of registers 1, 2, and 3 upon termination.
Consider the following TOY program. What is the value ofregister 3 upon termination?
- Write a program that reads in one integer a from standard input,and outputs a3.
- Write a program that reads in an integer a from standard inputand prints AAAA to standard output if
- a = 3
- a > 3
- a < 3
- a != 3
- a >= 3
- a <= 3
- Suppose that you load the following into locations 10-17 of TOY, set the PC to 10, and press RUN.
What, if anything, is printed to standard output if the following data appearon standard input?
Answer:The TOY programs reads two values from standard input.The first value is placed into memory location 15 whereit is eventually executed as code. This insertsa second add instruction.
- Repeat the previous question, but now with the following dataon standard input.
- Write a program that reads in three integers a, b, and c fromstandard input, and computes the discriminant d = b2 - 4ac.Use the multiplication function described above.
- Suppose that you load the following into locations 10-17 of TOY, set the PC to 10, and press RUN. The program reads in an integerfrom standard input and prints out a single integer to standardoutput. List all input values between 0123 and 3210 for which the program print 0000.
Answer: 0200 0400 0800 1000 2000.It returns 1 for all inputs that have at most one1 in their binary representation, i.e, the hexadecimal integers0000, 0001, 0002, 0004, 0008, 0010, ..., 8000.
- Suppose that you load the following data into memory locations30 through 37 before pressing RUN.
set the PC to 10, and press RUN.What will be the contents of memory locations 30 through 37 afterrunning the program?
- Translate the above TOY program into Java code by fillingin the ????.
- Suppose that you load the following into locations 10-1F of TOY, loadthe following data into locations 30-37,Suppose that you load the following data into memory locations30 through 37 before pressing RUN.
set the PC to 10, and press RUN.What will be the contents of memory locations 30 through 37 afterrunning the program?
- Suppose that you load the following into locations 10-1B of TOY, set the PC to 10, and press RUN. Suppose also that the following data is entered from standard input. What value is printed?
- Repeat the previous exercise, but with the following data on standard input.
- The following table shows the contents for the TOY registers and a section of TOY memory.Suppose that you set the program counter to 30 and hit run.What, if anything, is printed to standard output?List the final contents of registers 2 and 3 upontermination.
- Suppose that the data for memory locations D0 through E0 is as follows.What is the result of running linked.toy?Answer: 1 2 3 4 5 6 7.
- Change one word of memory in the previous exercise so that it prints out1 2 6 7 instead of 1 2 3 4 5 6 7. (linked list deletion)
- Change three words of memory (overwriting one, and using two more)so that it prints out 1 2 3 4 8 5 6 7. (linked list insertion)
Creative Exercises
- Maximum.Write a program max.toy that reads in a sequence ofnonnegative integers from standard input and prints out the maximumone. Stop reading in integers as soon as you encounter a negativeinteger.
- Magic swap.Write a TOY code fragment that swaps the contents of registers A and B, without writing to main memory or anyother registers. Hint: use the XOR instruction.
- 32-bit integers.Represent a 32-bit two's complement integer in TOY with twoconsecutive words of memory or registers (big endian or little endian).Explain how to add two 32-bit integers.
- Gray codes.Write a TOY program graycode.toy that reads inan integer n (between 1 and 15) from standard input and then prints out(i >> 1) ^ i to standard output for i = 2n - 1through 0.The resulting sequence is called aGray codeof order n.See Exercise XYZ in Section 5.1.
The Visual X-TOY Simulator uses the LCD display to show standard output.It is instructive to watch the alternate standard output (the tape punch card)and see the individual bits (8 per row).
- Greatest common divisor.Write a program gcd.toy that readsin two integers from standard input and prints theirgreatest common divisor to standard output.Write a function that assumes that registers A and B contain two input integers, output the value in register C, and returnsto the address stored in register F.You may use the following (inefficient) algorithm:
- One-time pad.Implement a one-time pad in TOY to encrypt and decrypt 256 bitmessages. Assume that the key is stored in memory location 30 - 3Fand that the input consists of sixteen 16-bit integers.
- Dot product.Compute the dot product of two arrays, which start atlocations RA and RB and have length RC.
- Axpy.Given a scalar a, a vector x, and a vector b, computethe vector ax + b.
- Find the singleton number.Suppose that a sequence 2N+1 16-bit integers appears on standard input such that N integers appear exactly twice and one integer appears only once. Write a TOY program to find the singelton integer.
Hint: XOR all of the integers together.
Simple Slot Machine Java Code
Last modified on August 02, 2016.
Copyright © 2000–2019Robert SedgewickandKevin Wayne.All rights reserved.