Loops
Loops
LoopEx.java
- while
- for
- do while
- break and continue (are often dumb)
Deitel 4.8-4.11, 5.1-5.5, 5.8
In a main, we will create a menu-driven program.
If you already feel comfortable with methods, feel free to add methods other than main to make it easier to break this code
down. Methods called by main
must also be marked static. If you would prefer to work in a separate
class with methods and instance variables you may do so, but think carefully
about what your class represents and what makes sense (not just is convenient)
to have as an instance variable.
Part A
In the main menu, the user has the options Enter Numbers, Draw Tables, or
Quit. The menu should keep offering these options until they choose
Quit.
If they choose to enter numbers, read in 10 ints from the user. If
any input is outside the range [0, 100], using a do-while make the user enter
that one again until it is in the right range (numbers outside the range don't
count towards the 10).
At the end of reading them in, print out the largest and second largest numbers
read in.
Then return to the main menu.
Part
B
If they choose to draw tables, we will need a low and a high value, which
start as 1 and 10 (but can be changed by the user).
Offer the user a menu with choices Choose Range, Sum Table, Return to Main Menu,
or RageQuit. The menu should
keep offering these options until the user chooses Return to Main Menu,
which goes back to Main Menu or RageQuit, which uses a labeled break to end the
whole program menu
If they want to Choose Range, ask for values for low and high.
[EC] Check that both values
are between (inclusive) 1 and 10, and low is less than high. Keep asking the user for new values until
they give a valid pair (don't accept half of a non-valid pair).(end EC)
If they choose Sum Table, print a table of sums using nested loops,
low+low up to
high + high, with labeled rows and columns.
Then return to this menu
If low is 3 and high is 7, the table might look like 3 4 5 6 7
--------------------
3 | 6 7 8 9 10
4 | 7 8 9 10 11
5 | 8 9 10 11 12
6 | 9 10 11 12 13
7 | 10 11 12 13 14
You may use separate loops for the column headers and horizontal line,
but the rest of each table should be done in a single set of nested loops. Make your numbers line up in columns as shown,
for all possible ranges.
[EC] also offer Difference Table and Product Table
as options, which go from low-low to high-high, or low*low to high*high, with
numbers that line up as shown, and
might look like (don't forget about making the columns line up, in all
cases).
3 4 5 6 7
-------------------------
3 | 0 -1 -2 -3 -4
4 | 1 0 -1 -2 -3
5 | 2 1 0 -1 -2
6 | 3 2 1 0 -1
7 | 4 3 2 1 0
3 4 5 6 7
--------------------
3 | 9 12 15 18 21
4 | 12 16 20 24 28
5 | 15 20 25 30 35
6 | 18 24 30 36 42
7 | 21 28 35 42 49