How to use loops in Java - java

I need help on how to use for-loops in Java
This is an assignment for class, so I'd rather just be pointed in the right direction instead of given an answer.
"List of valid seven dwarfs: Sleepy, Bashful, Doc, Sneezy, Happy, Grumpy, Dopey
Pool of random characters, non-valid Dwarfs: Lion-O, Cheetara, Panthro, Tigra, Snarf, Donald Duck, Mickey Mouse, Minnie Mouse, Goofy, Heathcliff, Huey, Dewey, Louie, Scrooge McDuck,
Declare these variables:
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
Print a list of three choices to the console. Ask the user to pick the correct dwarf of the three choices.
The list of three choices will include two names from the random characters list and one name from the seven dwarfs.
You will create a switch statement to handle the choice selection
When the wrong case is selected then decrement the int variable called counter and print to the console “wrong selection”
When the correct case is selected then change the corresponding boolean variable to true (ie.. firstSelection, secondSelection, etc) and print to the console “Hi Ho, you picked the correct one”
The default case will print a statement to the console “invalid selection”
Create a loop that will perform this seven times until you covered all seven dwarfs.
Use a for loop
Recreate the loop again using a do-while loop
Recreate the loop again using a while loop
At the end, create an if-else statement. This statement will have short circuit &&’s that will test all of the Boolean variables. If true, print a statement to the console “You earned a gold star!”. Else, print a statement to the console “You did not get all correct”. "
I completed the previous assignment, which was just this specification without the loops, with no problem. However I really don't understand how the professor wants us to integrate the loops into the problem. The only thing I can think of is that he wants up to create a loop seven times that somehow asks about a different dwarf each of the seven times. Is that even possible? Can you change the content of the loops as you are running through it? I feel like I am just not even thinking about this correctly.
Here is my code from the previous assignment, sans loops:
import java.util.Scanner;
public class SevenDwarfs {
public static void main(String[] args) {
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Sleepy");
System.out.println("2 Lion-O");
System.out.println("3 Cheetara");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hi Ho, you picked the correct one");
firstSelection = true;
break;
case 2:
System.out.println("Wrong selection");
--counter;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Panthro");
System.out.println("2 Bashful");
System.out.println("3 Tigra");
Scanner input2 = new Scanner(System.in);
int choice2 = input2.nextInt();
switch (choice2) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
secondSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Snaf");
System.out.println("2 Doc");
System.out.println("3 Donald Duck");
Scanner input3 = new Scanner(System.in);
int choice3 = input3.nextInt();
switch (choice3) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
thirdSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Mickie Mouse");
System.out.println("2 Sneezy");
System.out.println("3 Minie Mouse");
Scanner input4 = new Scanner(System.in);
int choice4 = input4.nextInt();
switch (choice4) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fourthSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Heathcliff");
System.out.println("2 Happy");
System.out.println("3 Goofy");
Scanner input5 = new Scanner(System.in);
int choice5 = input5.nextInt();
switch (choice5) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fiveSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Huey");
System.out.println("2 Grumpy");
System.out.println("3 Dewey");
Scanner input6 = new Scanner(System.in);
int choice6 = input6.nextInt();
switch (choice6) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sixSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Scrooge McDuck");
System.out.println("2 Dopey");
System.out.println("3 Louie");
Scanner input7 = new Scanner(System.in);
int choice7 = input7.nextInt();
switch (choice7) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sevenSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
if (firstSelection == true && secondSelection == true
&& thirdSelection == true && fourthSelection == true
&& fiveSelection == true && sixSelection == true
&& sevenSelection == true) {
System.out.println("You earned a gold star!");
} else {
System.out.println("\nYou did not get all correct.");
}
}
}

The fact that you realized you might be thinking about the concept incorrectly and asked for help is a good thing.
Read the following to get familiar with loops in Java.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To answer your question, yes, you can change the content of a loop as you run it. That's what variables are for. You can modify their values as your program runs. Look at this sample. The variable i increments with every iteration of the loop. The variable outsideLoop also changes inside the loop. Play with this and you'll start to understand.
class ForDemo
{
public static void main(String[] args)
{
int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
outsideLoop += i;
System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);
}
}
You've got a good starting point for the process of printing the selection, getting user input, and validating user input. Repeat that chunk (in a loop) 7 times.

Related

Can we add a back feature to a do while menu selector in java?

So I was working on a project for university, and I decided to use the classic do-while loop with a switch case in it to make a selector menu, but I want it instead of it asking the user for another case immediately after performing one, I want kind of like a back menu button, I searched the web but couldn't find a similar question to mine.
I included my code down below, so for example if I chose case 1, it will print "case 1" and then reprint the menu, but I want it to hold until the user enter an input then it will loop to the menu again.
Any help would be appreciated and thank you in advance.
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
break;
case 2:
System.out.println("case 2");
break;
case 3:
System.out.println("case 3");
break;
case 4:
System.out.println("case 4");
break;
case 5:
System.out.println("Exiting in process...");
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
break;
}
} while (operator != 5);
input.close();
}
}
Here is the answer to your question:
import java.util.Scanner;
// Import java.util for TimeUnit
import java.util.concurrent.TimeUnit;
public class Main {
// Create the wait function
public static void wait(int ms){
try {
Thread.sleep(ms);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
/** Add wait(3000); to every line! This will allow
the code to hold 3 seconds before returning back to the menu**/
wait(3000);
break;
case 2:
System.out.println("case 2");
wait(3000);
break;
case 3:
System.out.println("case 3");
wait(3000);
break;
case 4:
System.out.println("case 4");
wait(3000);
break;
case 5:
System.out.println("Exiting in process...");
wait(1000);
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
wait(3000);
break;
}
} while (operator != 5);
input.close();
}
}
I used a TimeUnit util to create a wait function. This wait function works as:
wait(int ms)

Understanding Java while loops

Hi am new to java programming and I am trying to understand while loops. I haven't used it in the code below but I have an assignment that requires me to. What I want the program to do is simply re prompt the user to enter a menu option 1 to 5 when the code in the switch statement executes based on the user input. I am unsure where to put the while loop in the code and also what to write inside of it. Can someonme please help me with the program I am to create? It also requires me to use a switch statement to evalute the user input. All comments would be appreciated!
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
get_method();
}
public static void get_method() {
int num;
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}
If I understand your question correctly you will want to put the while loop around the call for the action. In your case you have not specified if one of the options exits or on what condition the program should exit. In that case I have to assume that it loops indefinently. The code could be as below.
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
while(true) {
get_method();
}
}
public static void get_method() {
int num;
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}
The addition would be the
while(true) {
get_method();
}
You could also restructure it to add a continue option. Or to exit on one of the options say option 5 is the exit option than the program could be written as follows:
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
get_method();
}
public static void get_method() {
int num;
while(num != 5) {
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}
}
There are a number of different ways to handle loops but this should get you started.
do_While loop is best for menu driven application as per your code structure
do{
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
System.out.println(" menu option 1");
System.out.println(" menu option 2");
System.out.println(" menu option 3");
System.out.println("menu option 4);
System.out.println(" menu option 5");
int num= menu.nextInt();
switch (num) {
case 1:
System.out.println("You entered menu option 1");
//you can write while loop here or
// call new method which deals with while loop
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 5");
break;
case 0:
System.out.println("you entered menu option ");
exit(0);
break;
default:
System.out.println("You entered an invalid option");
break;
}
System.out.println("do you want to continue? Y/N");
}while(choice!='Y');

Adding a loop to a displayed menu so that it is displayed repeatedly until the last option is selected and stop the loop

I have created a display menu and want to add a loop to continuously display the menu until the last option is selected. Not sure if I am doing it right.
Let me know if there is anywhere I can add on thanks!
import java.util.Scanner;
public class loopTest
{
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit");
System.out.println("Please enter your choice: ");
}
public void start()
{
Scanner console = new Scanner(System.in);
String s = "";
while(s < size())
{
displayMenu();
console.nextLine();
switch (s.charAt(0))
{
case 'A': System.out.println("A. Option #A"); break;
case 'B': System.out.println("B. Option #B"); break;
case 'C': System.out.println("C. Option #C"); break;
case 'D': System.out.println("D. Option #D"); break;
case 'X': System.out.println("X. Exit"); break;
default: System.out.println("Error, please enter a valid
character");
}
}
s++;
}
}
consider using a boolean variable
boolean wantToExit = false;
while (!wantToExit ) {
.... // switch
case 'X':
wantToExit = true;
System.out.println("X. Exit");
break;
}
note
s is a string, there is no < comparator nor s++ incrementor
Also, you are not assign a value to s from the Console input

Loop back to program after an exception is thrown

public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
do {
try {
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice = Option.nextInt();
switch (Choice) { //used switch statement instead of If else because more effective
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
System.out.println("Invalid Entry");
throw new Exception();
}
} catch (Exception e) {
System.err.println("Enter Correct Input");
return;
}
} while (true);
}
I am trying to make it when users enter incorrect input type like a letter , the exception is caught and then returns back to the menus, right now it catches the exception but it doesnt stop running I have to force stop the program. So I added a return but that just displays the exception error and stops, how can I make it return back to the menus?
That is because you're returning from the method itself in the catch block.
And Do not throw exceptions like that. Just use some boolean to know if the choice is valid and loop until the choice is entered correctly.Prefer not to use while(true), instead rely on a boolean flag everytime like below,
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
boolean isValidChoice = false;
do{
isValidChoice = false;
Choice = 0;
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
if(Option.hasNextInt()){
Choice= Option.nextInt();
isValidChoice = true;
}
switch (Choice)
{
case 1:
CreateAccount();
break;
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
isValidChoice = false; //if invalid choice, then set flag to loop
System.out.println("Invalid Entry");
}
} while (!isValidChoice);
}
Move the "try {" after the "System.out.println("Please choose");" line.
you just need to remove the return in the catch. also just as a tip, you can get rid of the do while and just have a while loop, because the loop is never ending.
} catch (Exception e) {
System.err.println("Enter Correct Input");
}
Okay so I'm pretty sure this should work:
Create a boolean value outside of while loop that is holds if there was a valid input
boolean validInput = true;
In default set this value to false (meaning there is an invalid input)
default:
System.out.println("Invalid Entry");
validInput = false;
throw new Exception();
Make sure the catch statement is still in the do loop because the throw clause will halt normal execution and transition into exception execution. Next the while tester will test if there was a valid input
while(!validInput)
Lastly go up to the top of the do loop and set validInput to true. This will make it so that each time you clear the previous incorrect input.
This should work.

Initialize An Array of Ints with Variables

I want to make an array of integer values that represent counters so I initialized it like this in my main method:
int [] counters = new int [7];
counters [countListAll] = 0;
counters [countEmployeeReport] = 0;
counters [countDivisionReport] = ;
counters [countSalaryReport] = 0;
counters [countRetirementReport] = 0;
counters [countMain] = 0;
counters [countOthers] = 0;
And now I have to pass this array to my menu() method so that I can increment each counter each time any of the options is chosen.
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [countListAll] ++;
break;
case 'E':
case 'e':
employeeReport();
counters [countEmployeeReport] ++;
break;
case 'D':
case 'd':
divisionReport();
counter [countDivisionReport] ++;
break;
case 'S':
case 's':
salaryReport();
counters [countSalaryReport] ++;
break;
case 'R':
case 'r':
retirementReport();
counters [countRetirementReport] ++;
break;
case 'Q':
case 'q':
counters [countMain] ++;
break;
else
{
menu();
countOthers++;
}
}
Am I initializing the array correctly and passing it into menu() method correctly? And am I allowed to increment the objects like that?
EDIT: I changed the code, and this is the new code
Main method:
int [] counters = new int [7];
counters [L] = 0;//listAll
counters [E] = 0;//employeeReport
counters [D] = 0;//divisionReport
counters [S] = 0;//salaryReport
counters [R] = 0;//retirementReport
counters [Q] = 0;//quit
counters [O] = 0;//others
Menu Method:
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [L] ++;
break;
case 'E':
case 'e':
employeeReport();
counters[E]++;
break;
case 'D':
case 'd':
divisionReport();
counters [D]++;
break;
case 'S':
case 's':
salaryReport();
counters [S]++;
break;
case 'R':
case 'r':
retirementReport();
counters [R]++;
break;
case 'Q':
case 'q':
counters [Q]++;
break;
}
}
else
{
menu();
counters [O]++;
}
}
And FinalStats Method:
public static void finalStats(int [] counters)
{
System.out.println("Number of times listAll() was accessed from menu() is: " + counters[L]);
System.out.println("Number of times employeeReport() was accessed from menu() is: " + counters[E]);
System.out.println("Number of times divisionReport() was accessed from menu() is: " + counters[D]);
System.out.println("Number of times salaryReport() was accessed from menu() is: " + counters[S]);
System.out.println("Number of times retirementReport() was accessed from menu() is: " + counters[R]);
System.out.println("Number of times 'Quit' was chosen from menu() is: " + counters[Q]);
System.out.println("Number of times any other key was pressed in menu() is: " + counters[O]);
}
Yes, in general. There appears to be a bug with your countOthers logic. although nesting a switch with-in an if seems an odd choice, it would be much more readable with a simple if else-if chain (and you could use Character.toLowerCase(char) to handle mixed case. Something like,
if-else
public static void menu(int[] counters) {
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available.");
System.out.println("Enter 'E' to dislpay information on a particular employee.");
System.out.println("Enter 'D' to display division information.");
System.out.println("Enter 'S' to display salary information.");
System.out.println("Enter 'R' to display retirement information.");
System.out.println("Enter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = Character.toLowerCase(first.charAt(0));
if (first1 == 'l') {
listAll();
counters[countListAll]++;
} else if (first1 == 'e') {
employeeReport();
counters[countEmployeeReport]++;
} else if (first1 == 'd') {
divisionReport();
counter[countDivisionReport]++;
} else if (first1 == 's') {
salaryReport();
counters[countSalaryReport]++;
} else if (first1 == 'r') {
retirementReport();
counters[countRetirementReport]++;
} else if (first1 == 'q') {
counters[countMain]++;
} else {
menu();
counters[countOthers]++; // <-- instead of countOthers++
}
}
switch-case
It is also possible to express the above if-else chain with switch-case and something like,
switch (Character.toLowerCase(first.charAt(0))) {
case 'l':
listAll();
counters[countListAll]++;
break;
case 'e':
employeeReport();
counters[countEmployeeReport]++;
break;
case 'd':
divisionReport();
counter[countDivisionReport]++;
break;
case 's':
salaryReport();
counters[countSalaryReport]++;
break;
case 'r':
retirementReport();
counters[countRetirementReport]++;
case 'q':
counters[countMain]++;
break;
default:
menu();
countOthers++;
}

Categories

Resources