Java duplicate local variable. Stumped - java

I am brand new to coding and trying to get my second program working. It is pretty straight forward as to what it does, but it is throwing an error on line 24 "Duplicate local variable confirm". Can't quite work out why it doesn't like what I'm doing.
Scanner userInput = new Scanner(System.in);
char confirm;
do{
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is" + name + ", you are" + age + "years old and you would like to visit" + country + "?");
System.out.println("Press Y to continue or N to start over");
char confirm = userInput.next().charAt(0);
if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');

You're declaring confirm twice. Change the second declaration to just assigning to it and you should be OK:
confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it

Because your "confirm" variable already defined in the scope (second row). If you want to assign a value, just write confirm = userInput.next().charAt(0);

Another option to fix is to remove the unnecessary declaration char confirm;
And use it only when needed
char confirm = userInput.next().charAt(0);
As #ScaryWombat suggested, you will need to change scope of the variable (currently while is in different scope than do )

It seems apart from re-declaration of the variable confirm there are one or more issue -
Issue 1:
After int age = userInput.nextInt(). It won't prompt for country input and will prompt Press Y to continue or N to start over.
Cause of this issue:
Since you are using int age = userInput.nextInt(); the scanner will only take the integer value from the input and will skip the \n newline character.
Fix
As a workaround, I've added userInput.nextLine(); after int age = userInput.nextInt(); such that it will consume the \n character after nextInt().
Issue 2:
After the 1'st iteration, this line will cause issueconfirm = userInput.next().charAt(0);.
Cause of this issue:
In 2'nd iteration you won't get a prompt to enter the name as the line String name = userInput.nextLine(); will take \n from the last iteration as input and will skip and prompt for age How old are you?.
Fix
As a workaround, I've added userInput.nextLine(); after confirm = userInput.next().charAt(0); such that it will consume the \n character after userInput.next().charAt(0) and the next iteration will go as expected.
Issue 3:
This logic if (confirm !='y' || confirm !='n') expects only y and n in lowercase but here while(confirm == 'Y'|| confirm == 'y') you are expection y and Y both.
Fix - I've added the necessary changes in the code below but would recommend you do change it to a switch case.
NOTE:
It is not recommended to do userInput.nextLine() after every input and you could simply parse it. See here for further information.
I'm not recommending it but this will get you program working
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
Recommending that you use switch case instead of if comparasion of confirmation and parse the character and integer input and remove the arbitary userInput.nextLine() added as workaround.

Related

IDE prints both lines before I can parse user's inputs

so I am currently having difficult trying to fix this. In short, I'm trying to create a banking application for a class. I'm writing a method to print and get user's inputs but the print lines print out both lines before I can get inputs. Here is my implementation.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
What I expected it to do was to print out "Input your username" then after I get the user's input for it then to print the next line. However, what happening right now is that both lines get print before I can put in anything.
Thank you in advanced.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
This should work now. I have added a scanner.nextLine() after inputing choice

Why nothing gets printed after while loop?

I am writing a simple bank application. In my program I have used a while loop. In case a user enters wrong input it will re-prompt to enter again.
Now the problem is I am not able to write any system.out.print statement after the loop. It always shows error (says: unreachable statement), and eventually the line doesn't get printed out.
HOW CAN I FIX THIS?
[The reason I need to use system.out.print because I want to print all the info the user has input.]
The program I am working on:
package bankapplication;
import java.util.Scanner;
public class BankApplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO OUR BANK!\n\nPlease give all the inofrmation correctly.");
System.out.println("Enter your name: ");
String name = input.nextLine();
System.out.println("");
System.out.println("Enter your SSN: ");
String ssn = input.next();
System.out.println("");
System.out.println("Enter your Address: ");
String address = input.next();
System.out.println("");
System.out.println("Enter your telephone nr: ");
String teleNum = input.next();
System.out.println("");
while (true) {
System.out.println("Choose an account number for you (Between 5 and 10 positive numbers): ");
int accNum = input.nextInt();
System.out.println("");
if (accNum < 0 && accNum > 10 && accNum < 6) {
System.out.println("Invalid choise!");
} else {
System.exit(0);
}
}
System.out.println("Congratulation! Your new account has been created!");
System.out.println("The following is your account info:\n");
System.out.println("name: " + name + "SSN: " + ssn + "Address: " + address + "Tele. Num: " + teleNum + "Acc num: " + accNum);
}
}
When you invoke System.exit the entire program exits and the process is terminated. Instead you could replace the else statement with:
else { break; }
That will break the current loop and the rest of the statements will be printed. The keyword break simply breaks the loop.
You have a while (true) loop - a loop which is infinite unless something in the loop breaks out of it. The only line you have that breaks out of the loop is System.exit(0), which will end your program entirely. Therefore it is impossible to reach the code after your loop.
If you mean to break out of the loop in your else clause, use a break statement instead of exiting the program.
Note however that your if condition will never be true.
if (accNum < 0 && accNum > 10 && accNum < 6) {
accNum can never be less than zero and greater than 10.
You need to figure out what condition you actually want to check.
the condition
(accNum < 0 && accNum > 10 && accNum < 6)
can never be acheived , there is no way a number can be negative and >10 at the same time...the System.exit(0) will always be called on first loop.
That and when u call System.exit(0) you are exiting the program not the loop, therefor you will never reach the statement you are talking about .
you should either use
break;
or if you would like more prestige, put the right condition in the while(condition) ... try not to get used to using break ;

I'm having an issue with booleans apparently, textbased game

Scanner sc = new Scanner (System.in);
String enter = new String ("Enter your name brave soul: ");
System.out.println (enter);
String name = sc.next();
System.out.println ("Your name is: " + name + "? Y/N");
boolean y = true;
boolean n = false;
String yesorno = sc.next();
String intro1 = new String ("Welcome to Urieka! The objective of this game is quite simple, just find the key to escape.");
if (true) {System.out.println (intro1);} //here
else if (false) {System.out.println (enter);} //here
I'm having a problem, I want to print intro1 if the user inputs y and I want the prompt to enter the name if they input it incorrectly. Its currently ONLY printing intro1 regardless if I input y or no.
Furthermore, is there a way for me to run that scanner again because I assume that if I DO get this working and the user inputs n/false, then it would just print "Enter your name brave soul" and nothing else. Would I somehow have to add a scanner into the statement on the else if line?
if (true) {System.out.println (intro1);} //here
this is always true and will always run. The else will likewise never run.
You want instead
if ("y".equalsIgnoreCase(yesorno)) {
//...
}
Well... true is always true so
if (true) { ... }
will always be executed. You should do something like :
System.out.println("y".equalsIgnoreCase(yesorno) ? intro1 : enter);
You never change these booleans:
boolean y = true;
boolean n = false;
Also try to avoid usage of if(true), as mentioned in previous post:
if (true) {System.out.println (intro1);} //here
It is not mandatory to use a constructor when instantiating a String object:
String enter = new String("Enter your name brave soul: ");
// IS THE SAME AS <=>
String enter = "Enter your name brave soul: ";
Here is my solution of your problem:
Scanner scanner = new Scanner(System.in);
boolean correctName = false;
String name = "";
while(!correctName){ //== Will run as long "correctName" is false.
System.out.println("Enter your name brave soul: ");
name = scanner.next();
System.out.println("Your name is: " + name + "? Y/N");
String yesorno = scanner.next();
correctName = "Y".equalsIgnoreCase(yesorno); //== changes the boolean depending on the answer
}
System.out.println("Welcome to Urieka" + name + "! The objective of this game is quite simple, just find the key to escape.");
If (true) means that it will always enter the if condition and it will always print intro01 as it's doing.
The else condition will never be reached.
your condition should be something like:
if("y".equalsIgnoreCase(yesorno))
System.out.println (intro1);
else
System.out.println (enter);

Do while loop not printing correctly after 1st loop

I am trying to do a do-while loop that makes the program iterate again after the user inputs "y" or "Y", but everytime i run the program, It prints out something like this:
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box] (I enter y)
Are you a student? (no input box is shown, and it skips it)
Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)
How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box]
this is what my program looks like:
import java.util.Scanner;
public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;
do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();
System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();
System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();
if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}
if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}
if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
}
while(repeat == 'y' || repeat == 'Y');
}
}
i am a beginner to programming, so any help would be good. Thank you.
At the end of the loop you call next() to read the "try again" response. This reads the next token, but still leaves the line ending on the input stream.
Next time through the loop, when you call nextLine() to read the "are you a student" response, it simply reads the remainder of that line immediately.
The easiest solution is:
Use nextLine() instead of next() for your "try again" prompt, but then this means you'll have to take care of the line ending left by nextInt() in the "tickets" question, so then you'll also have to...
Use nextLine() instead of nextInt() for your "tickets" question, then use Integer.parseInt() to parse the string into an int.
An alternate option, since all your responses seem to be just single-word responses, is to use next()/nextInt() everywhere and not use nextLine() at all. The point is, when you mix the two, you have to be aware of how they interact.
The issue lies in this block of code:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
When you call keyboard.next(), it doesn't read the entire line, so when your program loops again, the next time you call keyboard.nextLine(), it takes in part of what you entered previously in the loop and it gets ahead of itself.
The best solution would be to add a keyboard.nextLine() after you call keyboard.next() so that the remainder of the line will be consumed and won't be left over to mess up future iterations of the loop.
So for example you could change it like this:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
keyboard.nextLine();
repeat = input.charAt(0);

Validation for Negative numbers

System.out.print("Price of the book? ");
while (!keyboard.hasNextDouble() || priceOfBook <=0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}
priceOfBook = keyboard.nextDouble();
I am trying to validate the above code basically so that user can't enter negative numbers or letters or empty doubles but it's not working and I can't see where I'm going wrong. Can someone please help me?
So how i understand you need to real line until the user didint enter negative or letter.
Scanner sc = new Scanner(System.in);
double x = 0;
System.out.println("Enter price");
while (true) {
if (!sc.hasNextDouble()) {
System.out.println("Sorry price cant be negative or be letter");
break;
}
System.out.println("Enter price");
x = sc.nextDouble();
}
Hope it helps!
You put
priceOfBook = keyboard.nextDouble();
outside of your while loop :) Try like this:
while (priceOfBook <= 0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
priceOfBook = keyboard.nextDouble();
}
So that it will keep asking the user if he enters a number < 0.
You don't assign the user's input to priceOfBook until after the while loop. So, when your loop checks if priceOfBook is negative, it doesn't check the user's input, but the previously stored value (if there is one). This allows the user's input (even if it's negative) to pass the while loop, and then get saved as priceOfBook.
Try instead:
while (!keyboard.hasNextDouble() || priceOfBook = keyboard.nextDouble() <=0) {
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}

Categories