I am pretty new to Java. Sorry if this is a lame question. I have this chunk of code. It is not the whole thing obviously.
char option = scan.next().charAt(0);
for (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
}
int lengthOne = stringOne.length(); //Getting the lengths for each string
int lengthTwo = stringTwo.length();
if (option == 'a'|| option == 'A') { //If the user inputs a
if (lengthOne == lengthTwo) { //If both lengths are equal
System.out.println("The strings are the same length");
}
Looking for some advice on which loop i should use for this code. The options will be A-F and then Q to quit.
The while loop can seem messy for what you are trying to accomplish. I would use a Switch statement inside a 'do while' loop.
If the user input doesn't match a 'case' then it will go to the default.
When a user enters 'q' to quit then boolean validSelection turns to true and you will exit the 'do while' loop.
public static void main( String[] args )
{
Scanner scan = new Scanner( System.in );
boolean validSelection = false;
do
{
System.out.println( "Please pick an option from the menu above" );
char option = scan.next().charAt( 0 );
switch( option )
{
case 'a':
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':
break;
case 'f':
break;
case 'q':
validSelection = true;
break;
default:
System.out.println( "Choice invalid." );
break;
}
}
while( validSelection == false );
}
}
Add a scan inside the loop.
char option = scan.next().charAt(0);
while (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
Try this
Scanner scan = new Scanner(System.in);
char option = scan.next().charAt(0);
while (option != 'a' && option !='b' && option != 'c'&& option !='d'&& option !='e'&& option !='f'&& option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
You will need the ANDs instead of the ORs or it wont work
Related
I'm struggling with learning validation loops in Java. I know how I need it to work but I can't seem to get it written.
If you select a character other than A, B, or C you receive an error
while (selection != A && !=B && !=C )
I also tried:
while (Selection != 'A' )
{
if (Selection != 'B')
else if (Selection != 'C')
else System.out.println ("Invalid Entry. Please make another selestion");}
Thank you for any help.
What can help in more complex systems is a case statement:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter A, B or C: ");
String input = scanner.nextLine();
switch(input) {
case "A":
// do something for A
break;
case "B":
// do something for B
break;
case "C":
// do something for C
break;
}
}
Here I used an infinite loop. So for the user to get out of it, one of the options should break it. Therefore I'd add a quit option:
Scanner scanner = new Scanner(System.in);
endless: while (true) {
System.out.print("Enter A, B, C or quit: ");
String input = scanner.nextLine();
switch(input) {
case "A":
// do something for A
break;
case "B":
// do something for B
break;
case "C":
// do something for C
break;
case "quit":
break endless; // break the while loop, not just the switch
}
}
On the other side, if you just want to ensure you have one of the values A, B or C input and then continue with exactly that value, use
Scanner scanner = new Scanner(System.in);
String input = null;
endless: while (true) {
System.out.print("Enter A, B or C: ");
input = scanner.nextLine();
switch(input) {
case "A":
case "B":
case "C":
break endless;
}
}
System.out.println("Thank you for choosing " + input);
Using the new switch with arrow, without break and with comma separated case values:
Scanner scanner = new Scanner(System.in);
char answer = ' ';
while (answer == ' ') {
System.out.println("Enter A, B, C or quit: ");
String input = scanner.nextLine();
switch (input) {
case "A", "B", "C" ->
answer = input.charAt(0);
quit ->
answer = 'q';
default ->
System.out.printf("Not A, B or C: '%s'.", input);
}
}
if (answer == 'q') {
System.exit();
}
Hey guys i have got a small weird problem here, i am asking the user to input their menu choice and depending on what they choose it calls a certain method.
I have used scanner.next() after some googling but for some reason only when i enter 1 or 2, i press enter and then press say 1 again and then it actually works. But what is weird that it calls options 3, 4, 5 and 6, immediately without me having to input the number twice.
I have tried with scanner.nextLine() after the scanner.nextInt() and that just leaves me having to put my option 1 or 2 in with no result.
while(exit == 0)
{
System.out.println("\n");
System.out.println("Menu 1: Display fullname of the user \n");
System.out.println("Menu 2: Display of user information \n");
System.out.println("Menu 3: Change password \n");
System.out.println("Menu 4: List all of users in the library full name\n");
System.out.println("Menu 5: Search for a book\n");
System.out.println("Press 6 to search for a books location in the library\n");
System.out.println("Press 0 to exit\n");
System.out.println("Enter choice: ");
int menuChoice = scanner.nextInt();
scanner.next();
if(menuChoice == 1)
{
displayUserFullName();
}
else if(menuChoice == 2)
{
displayUserInformation();
}
else if(menuChoice == 3)
{
menuForChangePassword();
}
else if(menuChoice == 4)
{
displayAllUserInSystem();
}
else if(menuChoice == 5)
{
searchBookByISBN();
}
else if(menuChoice == 6)
{
searchBookLocation();
}
else if(menuChoice == 0)
{
exit = 1;
}
}
Thank you in advance!
int menuChoice = scanner.nextInt();
scanner.next();
Read the javadoc for scanner. It waits for user input:
public String next(): [..] This method may block while waiting for input to scan
So in your program, you say: wait for user to type and int, then wait for user to type something.
Remove the scanner.next(); and it should work.
Scanner is a class parsing single tokens, like nextInt, nextDouble, nextToken (String). With corresponding testing methods: hasNextInt and so on.
All this parsing you do not need, so use nextLine for an entered line, or an other Reader class (InputStreamReader, BufferedReader).
Also you may utilize switch instead of if else if.
String menuChoice = scanner.nextLine();
switch (menuChoice) {
case "1":
displayUserFullName();
break;
case "2":
displayUserInformation();
break;
case "3":
menuForChangePassword();
break;
case "4":
displayAllUserInSystem();
break;
case "5":
searchBookByISBN();
break;
case "6":
searchBookLocation();
break;
case "0":
exit = 1;
break;
default:
System.out.printf("Unknown choice: '%s'%n", menuChoice);
}
menuChoice will contain the entire line, without line ending.
You might use an int with Integer.parseInt(menuChoice) but this would throw a NumberFormatException on wrong input, aborting your program. Scanner.nextInt would hang too, actually needing an hasNextInt().
import java.util.Scanner;
class MenuFastFood {
public static void main(String[] args) {
String s;
char order;
Scanner keyboard = new Scanner(System.in);
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
do {
switch(order) {
case 'A':
System.out.println("CheeseBurger");
System.out.println("Onion Rings");
System.out.println("Soda");
break;
case 'B':
System.out.println("Hot dog");
System.out.println("Fries");
System.out.println("Milk Shake");
break;
default:
System.out.println("error");
return;
case 'X':
System.out.println("EXIT");
break;
}
}while(order != 'X');
}
my program is suppose to pick an item based on the character enter in to keybaord and then loops back if another item is selected. when i run this and pick an item. it loops that item for ever. How do i get that to stop and makes it able for me to select another item?
Move your code for reading input to inside do..while
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
I have a code that has 4 cases and I am trying to break the loop and if the 'f' case is chosen. and then choose from that case. When i try to do the if statement with the break over 30 errors but when I take it away the code is fine.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}
You would use a Java label (see this code example named BreakWithLabelDemo.java) to tell your code where to break.
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}
For your implementation, it would make sense to break on a specific case before even entering the switch statement. For example:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
This seems to be a pretty simple way to exit the while loop without conflicting with the break statements of the switch statement.
Or if you still need to call the friendsList method when choice is 'f' you can move that if statement to after the switch statement.
Note: With this you should also remove the if statement at the bottom of your code example.
if (case == 'f')
What is case in this statement? You should replace that with choice.
if (choice == 'f')
you need to put if inside while loop.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}
The if statement should be moved inside of the while loop to be effective, and case inside the if statement should be changed to choice.
so
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}
I am writing a database program that allows the user to search for employees and it opens up a menu for them.in my Main() I have to prompt the User to press m to open up the menu() or q to open up finalStats() any other input is invalid. My problem is that i can't get a while loop to work properly. whenever i hit m it works and when i hit q it works fine, but whenever i hit a key other than those there's an infinite loop and it just infinitely prints out "Please enter a valid character"
boolean end = false;
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
while (end == false)
switch(entered)
{
case "m":
case "M":
menu();
case "q":
case "Q":
finalStats();
end = true;
default:
System.err.println("Please enter a valid character");
}
You need to move the line
while (end == false)
to before the scan.next(), to allow the user to try again. Make sure to add braces when you do this, so the while affects the entire program snippet you are showing. It is considered a good practice to always use curly braces for loops and if statements.
Also, as #RahulTripathi points out, you need to add break statements at the end of your case blocks.
You are missing the break statement in your switch case. Also move your while statement to allow user to scan.
Try this:
boolean end = false;
while (end == false)
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
switch(entered)
{
case "m":
case "M":
menu();
break;
case "q":
case "Q":
finalStats();
end = true;
break;
default:
System.err.println("Please enter a valid character");
}
I think this fixes your problems:
boolean end = false;
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
while (end == false)
{
switch(entered)
{
case "m":
case "M":
menu();
break;
case "q":
case "Q":
finalStats();
end = true;
break;
default:
System.err.println("Please enter a valid character");
break;
}
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
}
You have a couple of problems. You are missing break; in your cases and you are not soliciting new input inside of the while loop. I am not sure exactly what you are doing whether you want to solicit an option more than once.