I am new to switch loops and am having multiple problems with this currency converter program I am trying to create.
First, I would like to loop the case 1 where the user keeps entering values until they type -1 so it stops and moves on. At the moment, it does not do this. Once I've entered the GPR values on switch 1 and then loop back to the menu keeping the original GPR stored values.
Code is here:
import java.util.Scanner;
public class Conversion {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int Choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
Choice = input.nextInt();
switch (Choice) {
case 1:
while (!exchange.equals("-1"));{
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange (Type '-1' to stop) ");
}
case 2:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in euros are" + poundDollars);
case 3:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in euros are" + poundYen);
case 4:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in euros are" + poundRupees);
case 5:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in euros are" + poundEuro);
case 6:
break;
}
input.close();
exchange.close();
}
}
switch is not a loop. It's a branching statement like if. It has break, but that is only present because you can "fall through" to the next case statements. Currently you are falling through on most of them, because you've forgot putting in the break statements between the cases.
A switch statement isn't a loop. Consider it a replacement for a series of else-if statements. Your code actually reads more like this:
if(Choice == 1)
{
}
else if(Choice == 2)
{
}
else if(Choice == 3)
{
}
else if(Choice == 4)
{
}
else if(Choice == 5)
{
}
else if(Choice == 5)
{
}
However, your switch cases should be terminated with break statements. If one is not, unlike the else-ifs above, execution will fall-through to the next case and execute the code in that one too, until it finally reaches a break statement or goes through all the cases.
What you want is for your while-loop to wrap AROUND your switch statement, but you should fix your while-loop first, since you terminated it with a semicolon, it is infinite. While-loops don't need a semicolon at the end, unless you do not have a body for it but you do have some side-effect happening in the conditional check that will eventually cause it to end.
while( blah )
{
switch( blah )
{
case 1:
// Do stuff for this case
break;
case 2:
// Do stuff for this case
break;
default:
// Do stuff when no case is matched
break;
}
}
I think you're a bit confused. As noted by immibis in his comment, switch statements are not loops, so you need to enclose the switch statement inside a loop.
Then, you're missing the break statements at the end of each case. Quoting the Java tutorials:
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Your program should be something like this:
public static void main(String[] args) {
// Variable definitions
while(true) { // This is a little trick to force the application to repeat
// a task until you explicitly break the loop
// Code to print your menu
choice = input.nextInt();
if(choice == -1 || choice == 6)
break; // Break the while loop if choice is -1 or 6
switch(choice){
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
If you don't put those break statements at the end of each case block, your program will fall through every option.
Please read:
The Java tutorials: The switch statement
The Java tutorials: The while statement
Another option would be something like this:
public static void main(String[] args) {
// Variable definitions
/*
Now let's use a labeled loop
*/
menu: while(true) {
// Code to print your menu
choice = input.nextInt();
switch(choice){
case -1: // Nothing goes here, so the execution will fall through
// to the next case
case 6:
break menu; // This will break the menu loop.
// Since the previous case simply falls through to
// this one, this will happen if choice is
// either -1 or 6
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
More reading:
The Java tutorials: Branching statements
Related
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().
I'm trying to create a hotel menu in Java (I'm still learning the language) and I've run into an issue. I can make the menu open a new menu, but when I make a choice from that second menu, it constantly loops. I think it's the for loop that is causing the issue. Can anyone advise how I get the second menu entry to stop looping? Methods below:
Menu class method:
public void getMenu()
{
Floor floor = new Floor();
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Booking Menu");
System.out.println("Select from the options below");
System.out.println("1. Check room availability");
System.out.println("2. Display floor");
System.out.println("3. Display all availability");
System.out.println("4. Cancel Booking");
System.out.println("Please enter choice (press 8 to continue)");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: room.getRoomMenu();
break;
case 2:
break;
case 3:
break;
}
}
while (choice !=8);
}
That menu opens a second menu in this method:
public void getRoomMenu()
{
Floor f1 = new Floor(1);
Floor f2 = new Floor(2);
Floor f3 = new Floor(3);
Floor f4 = new Floor(4);
boolean check = false;
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Which Floor?");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: f1.displayFloor();
break;
case 2: f2.displayFloor();
break;
case 3: f3.displayFloor();
break;
case 4: f4.displayFloor();
break;
}
}
while(choice !=8);
kboard.close();
}
The second menu option should display the chosen floor which displays all rooms on that floor. This is the displayFloor method:
public void displayFloor()
{
/**
* Displays floor number and room display method
*/
System.out.println("Floor: "+floorNumber);
for(int counter=0;counter<rooms.length;counter++)
{
rooms[counter].display();
}
}
Both your while loops continue looping as long as choice != 8. And since you never modify the choice inside the loop, it will just continue looping (unless 8 was input by the user).
Also note that the break; you added are breaks for the switch-case, not to stop the do-while-loop. To have a break within the switch-case stop the entire do-while-loop, you should use a label to give the loop a name, and break that one. In addition, you should ask the user to give a new input if it didn't came into one of the switch-cases, otherwise it will still loop forever. So something like this:
choice = kboard.nextInt();
myLoop: do {
switch(choice) {
case 1:
f1.displayFloor();
break myLoop;
case 2:
f2.displayFloor();
break myLoop;
case 3:
f3.displayFloor();
break myLoop;
case 4:
f4.displayFloor();
break myLoop;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
choice = kboard.nextInt(); // Ask the user for a new input
break; // <- This break only breaks the switch, not the loop
}
} while(choice !=8);
If your intention was to continue looping until the user input 8, it should be something like this instead:
choice = kboard.nextInt();
do {
switch(choice) {
case 1:
f1.displayFloor();
break;
case 2:
f2.displayFloor();
break;
case 3:
f3.displayFloor();
break;
case 4:
f4.displayFloor();
break;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
}
choice = kboard.nextInt(); // Ask the user for a new input for the next iteration
} while(choice !=8);
The loop is occurring here:
while(choice !=8);
You need to make sure that the ending condition is always satisfied at some point to avoid unwanted infinite loops.
Maybe you meant if(choice != 8) rather than a do/while loop (which will keep running until choice is 8, which will only occur if the user inputs 8).
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.
import java.io.*;
import java.util.*;
public class Prog213c
{
public static void main(String[] args) {
Scanner kbReader=new Scanner(System.in);
do{
System.out.println( "Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits)
{
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default: System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
String answer = kbReader.next();
} while (answer == 'y'); // error received here
You have a few problems here:
String answer = kbReader.next();
} while (answer == 'y'); // error received here
Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.
This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".
Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.
You could do something like:
case 30:
case 31:
case 32: // ...
but that seems like a thoroughly painful way to do that. See also this question for more details.
This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).
Also:
int studentNumber = kbReader.nextInt();
You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?
Single quotes are character literals in Java. So you can't compare a
String with a char directly.
Your answer variable has to be declared before the do-while loop.
you have to use the equals method to compare strings.
answer.equals("y")
Problem 1:
since answer is a string object, this is not working (answer == 'y');
you can do "y".equals(answer) is you get the nextLine from the scanner
or if you need to work with chars
char x = kbReader.next().charAt(0);
while (x == 'y');
Problem 2:
answer must be declared before the do-while loop...
your final code can look like
Scanner kbReader = new Scanner(System.in);
char answer = 'y';
do {
System.out.println("Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits) {
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default:
System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
answer = kbReader.next().charAt(0);
} while (answer == 'y');
Change your while condition to:
while ("y".equals(kbReader.next()));
here is my code
import java.io.*;
import java.util.*;
public class weightOnOtherPlanets {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine( );
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " " ;
switch(p){
case 'A':
case 'a':
System.out.println(answerPhrase +(.091*weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720*weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865*weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612*weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
}
I have used almost the exact same code for another similar practice project and it worked just fine. When i run the program it goes to the point where it asks for a weight input, then it displays the choice list, but with the error message exception in "main":
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at weightOnOtherPlanets.main(weightOnOtherPlanets.java:14)
I don't know why it gives this error before allowing keyboard input for String choice.
This is because of the way Scanner scans lines.
After you enter a double (the weight), you press Return. This tells System.in to take all the characters you entered and pass them to the scanner. The scanner then reads the part that interests it - the double number - but leaves everything else waiting for the next operation.
This means the Return you pressed - the end-of-line - is still there. Now, the next thing is nextLine(). The scanner sees it, and it reads all the characters it has until it finds an end-of-line. But as we said, the end-of-line is right there. So it reads that, and gives you all the characters it found before it. Which is none at all, because there were no other characters between the double number and the end-of-line.
This means you get an empty string. And an empty string doesn't have a character at position 0, because that would mean it was not empty.
So what you should do is, after receiving the double, you should add a kbReader.nextLine(); - just like that, without putting the value anywhere. This will skip the end-of-line you entered for the double, and then you'll get the next line properly.
When you do your menu reading, though, you should be checking that the string is not empty before you call charAt(0). After all, the user can decide to press Return rather than make a valid choice. So your system should either ignore that or tell him that it's not a legal input, rather than fail with an exception.
You call nextDouble(); and after that you call nextLine() to get your answer phrase. But that call to nextLine(); will only consume the rest of the line on which you entered your double and it will be empty, therefore choice.charAt(0); will throw an exception.
Try doing something like this to consume the rest of the line and then call the nextLine() to get the answer phrase.
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
kbReader.nextLine(); // Consume the rest of the line
// ...
String choice = kbReader.nextLine(); // Get the actual input
char p = choice.charAt(0);
try this:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine();
if (choice.isEmpty()) {
choice = kbReader.nextLine();
}
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " ";
switch (p) {
case 'A':
case 'a':
System.out.println(answerPhrase + (.091 * weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720 * weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865 * weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612 * weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
You need to read for input differently. That's why you are throwing an exception.
char p = choice.charAt(0); // why not just do a string comparison instead?
is where the error comes up. This is because choice is null / has no charAt(0).
Irregardless I would use something like this instead
char p = ''
while(in.hasNext()) {
String input = in.nextLine();
if (p.length()>0){
p = choice.charAt(0);
}
//do whatever you wanted to with p
This should give you the behavior you are looking for.
Don't forget to consider changing the double input to work roughly the same though.
I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.