Switch Statement is making the first case skip a line - java

So I'm guessing that the solution to this is going to be really simple but I have no idea what I'm looking for so I'd like some help. What happens is that when I run the program, and choose case 1. It prints both "dog's name" and "dogs race" without giving me a chance to fill in the dogs name. So when I choose case 1 I start out only getting to fill in dogs race, how heavy, and how old it is! here is the code I'm using...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);

I believe you need to call nextLine() after your call to nextInt(), because that hasn't advanced the scanner to the next line yet.

There's a newline reminder from your first sc.nextInt, you can change the delimiter to \n or just call nextLine(); just after reading the option (Using sc.useDelimiter("\n") )

Try:
int option=Integer.parseInt(sc.nextLine());
This has both the effect of advancing the cursor to the next line and getting the typed number.

Related

Why does it run 3 times before asking for user input again?

It works fine with '1'but with the other options it runs 3x times (by printing out the whole Menu
thing before allowing user input again.
char a;
do {
System.out.println ("MENU");
System.out.println ("Press 1 to EXIT");
System.out.println ("Press 2 to PLAY");
System.out.println ("Press 3 for SETTINGS");
a = (char)System.in.read();
switch (a){
case '1':
System.out.println ("You have EXITED");
break;
case '2':
System.out.println ("GAME OVER");
break;
case '3':
System.out.println ("You chose SETTINGS");
break;
}
}while (a != '1');
By default the console (or similar) is line buffered, so you type a digit followed by return/enter. You are reading a character at a time. The three characters you see are the digit, Carriage Return (CR/'\r') and New Line (NL/'\n').
See this question How to read a single char from the console in Java (as the user types it)? Alternatively read a line at a time - most example programs will use java.util.Scanner.
You have to reset the a as '1'. The reason it was executing repeatedly is because the value of as is not reset

Program that asks a multiple-choice question won't show the user an answer after an invalid character is entered

I am trying to make a program where the user has to answer a multiple choice question. The program works completely fine when the user enters A, B, C, or D. But if they enter "Z" for example, it stops working at a certain point. The program will proceed as prompted by saying "Invalid answer, please enter A, B, C, or D." But when you select A, B, C, or D, the program suddenly ends instead of showing whether or not the user was correct.
I tried to call the getAnswer() method again as the default case in the switch statement, so the program will ask the user for their choice again. Before I added this line, it didn't do that at all. However, it's still not following through with that last step. Here's the code:
// Call the method that will ask the user the question.
askQuestion();
// Call the method that will allow the user to answer.
getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'b':
case 'B':
System.out.println("Correct!");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'c':
case 'C':
System.out.println("Incorrect! 'Float' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'd':
case 'D':
System.out.println("Incorrect! 'True' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
default:
System.out.println("Invalid character.");
// Repeats the getAnswer method to retrieve a valid character.
getAnswer();
}
}
// method that will ask the question
public static void askQuestion()
{
// Show the user the possible answers for the multiple choice questions.
System.out.println("Which of these is NOT a Java key word?");
System.out.println("A: switch");
System.out.println("B: keyboard");
System.out.println("C: float");
System.out.println("D: true");
}
// method that will retrieve the answer from the user
public static char getAnswer()
{
// create another Scanner object
Scanner keyboard = new Scanner(System.in);
// Tell the user to select their answer and store it in a variable.
System.out.println("Select your answer by pressing A, B, C, or D.");
String input = keyboard.nextLine();
userChoice = input.charAt(0);
// Return the user's answer to main.
return userChoice;
}
Ideally, if the user presses Z, but then presses A the next time around, it will tell the user is wrong, but the program is just ending instead of providing feedback. What am I missing?
It's best to use a loop here. You keep looping until the user enters a valid response:
askQuestion();
while (true) {
userChoice = getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
...
default:
System.out.println("Invalid character.");
}
}
Note that you don't need the break statements after each System.exit(0) call.
You could move the askQuestion() call inside the while loop if you wanted to re-ask the question on a bad input.
you can use a recurring method call when an invalid answer is received
public void doProcess(){ //this will keep getting called until a valid key is read.
askQuestion();
userChoice = getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
case 'b':
//program will exit/ correct wrong ans etc etc
break;
default:
//call itself again
doProcess();
}
}
Your switch case only checks for a single time only for the first answer.
You can have function for finidng the answer itself.
import java.util.Scanner;
public class Main
{
// method that will ask the question
public static void askQuestion()
{
// Show the user the possible answers for the multiple choice questions.
System.out.println("Which of these is NOT a Java key word?");
System.out.println("A: switch");
System.out.println("B: keyboard");
System.out.println("C: float");
System.out.println("D: true");
}
// method that will retrieve the answer from the user
public static char getAnswer()
{
// create another Scanner object
Scanner keyboard = new Scanner(System.in);
// Tell the user to select their answer and store it in a variable.
System.out.println("Select your answer by pressing A, B, C, or D.");
String input = keyboard.nextLine();
char userChoice = input.charAt(0);
// Return the user's answer to main.
return userChoice;
}
public static void main(String[] args) {// Call the method that will ask the user the question.
askQuestion();
// Call the method that will allow the user to answer.
char userChoice = getAnswer();
while(!checkForCorrectAnswer(userChoice)){
userChoice = getAnswer();
}
}
private static boolean checkForCorrectAnswer(char userChoice){
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'b':
case 'B':
System.out.println("Correct!");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'c':
case 'C':
System.out.println("Incorrect! 'Float' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'd':
case 'D':
System.out.println("Incorrect! 'True' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
default:
System.out.println("Invalid character.");
// Repeats the getAnswer method to retrieve a valid character.
return false;
}
}
}
To avoid having to use the case expression to verify if it is lowercase or uppercase, I recommend that you use the following:
String value = String.valueOf(userChoice).toUpperCase();
This helps to make the conversion of lowercase to uppercase before doing the evaluation in the switch case.

java currency calculator pausing swtich to give output back to user

first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.

Using switch statements in a while loop

I'm trying to use switch statements in a while loop in Java, but there is something going wrong. Please have a look at a sample code below which explains my problem:
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{ switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
If I run this code, the output is as follows:
1
Please enter amount
2000
1. Transfer
2.Check balance
3.Recharge
Please enter amount
2
1. Transfer
2.Check balance
3.Recharge
Please enter amount
When I enter the amount, I would then like to choose another option - and the output should be according to the option chosen (you should probably be knowing what I want this code to do). Could someone please help correct the code?
Thanks
You currently get and set the selection value once and before the while loop, and so there is no way to change this from within the loop. The solution: Get your next selection value from the Scanner object inside of the while loop. To understand this, think the problem out logically and be sure to walk through your code mentally and on paper as the issue is not really a programming issue but rather a basic logic issue.
Regarding:
Could someone please help correct the code?
Please don't ask us to do this and for several reasons.
This is not a homework completion service
You're harming yourself by asking others to change the code for you, as you learn how to code by writing code.
Really this is a basic simple issue that you have the ability to fix on your own. Please give it a try, and only if the attempt doesn't work, then show us your attempt.
You're forgetting to ask for the selection again. It's not going to change once it's been entered.
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
selection = input.nextInt(); // add this
}
You could even use a do...while loop instead to avoid writing input.nextInt(); twice
Scanner input=new Scanner(System.in);
int selection;
do
{
selection = input.nextInt();
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
while(selection < 4);
Case must be bigger than 4, in your case the cases are less than 4. so you won't quit the loop, basically the break statement breaks the switch and jumps to loop, but than the loop is again less than 4 so it jumps again into the switch and so on. Fix the Sizes of your cases, maybe just make an
(selection != 1 || selection != 2 || selection !=3 || selection !=4)

What is the proper way to get a char input(using Scanner) inside a loop in Java?

I am trying to make a simple calculator program where a user can opt to do an operation and enter the numbers as long as he/she wishes to.
I just have problem because whenever I would reach inside my loop and ask the user if he/she want to continue and whenever I would run the program, I would have an "Exception in thread "main" java.lang.NullPointerException"
Scanner myInput=new Scanner(System.in);
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
//get the numbers
//provide the menu
//get the user's choice
switch (calc)
{
case 1: out.println("Sum is: " +(num1+num2)); break;
case 2: out.println("Difference is: " +(num1-num2)); break;
case 3: out.println("Product is: " +(num1*num2)); break;
case 4: out.println("Quotient is: " +(num1/num2)); break;
case 5: out.println("Modulo is is: " +(num1%num2)); break;
case 6: out.println("Sum is: " +(num1+num2));
out.println("Difference is: " +(num1-num2));
out.println("Product is: " +(num1*num2));
out.println("Quotient is: " +(num1/num2));
out.println("Modulo is is: " +(num1%num2)); break;
default: out.println("Invalid."); break;
}
out.println("Compute another?");
ans=myInput.findInLine(".").charAt(0);
}
May I humbly ask what can I do with this program so that it will ask again for the user's input whether to continue or not? Thanks in advance for your help.
in this palce, best way is to use do-while
do{
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
//
//
//
}while ((ans=='Y')||(ans=='y'));
This will keep asking till the user's answer is 'Y' or 'y'.
I hope you can take care of other thing.
for using while loop.
System.out.print("Do you have numbers to compute?");
char ans=myInput.findInLine(".").charAt(0);
while((ans=='Y')||(ans=='y')){
//
//
//
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
}
The NullPointerException is being thrown as Scanner.findInLine() can return null if it does not find the requested String/Pattern. The code invokes the method charAt(0) on the null String. Changing the code to the following will resolve this:
Scanner myInput=new Scanner(System.in);
char ans;
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
// Code omitted
System.out.print("Compute another?");
myInput.nextLine();
String s = myInput.findInLine(".");
ans = (null == s) ? 'n' : s.charAt(0);
}

Categories

Resources