While loop NoSuchElementException integer input java - java

I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pin;
int selection = 0;
boolean valid = false;
do {
System.out.print("Please enter the password: ");
pin = console.nextLine();
valid = checkPassword(pin);
} while (!valid);
while (selection != 4 && valid == true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
}//main

Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.

Related

How to break scanner for certain statements and run for others

Im a SUPER beginner in programming and was doing some exercises and I need your help. I just simulated an ATM machine in the most basic way. I need your help in the part that says Press 1 Deposit or Press 3 Talk to a representative. I need the Scanner to break after that if user presses 1 or 3 as currently it is set so that if user will press 2 it will send them to the Withdraw statement where you can finish the transaction but right now its still executing for Pressing 1 and 3 and I cant think how to break that or change that. Thanks in advance
package june;
import java.util.Scanner;
public class Bank {
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
System.out.println("ENTER PIN");
int pin = 9876;
pin = scr.nextInt();
if (pin == 9876) {
System.out.println("Welcome To XYZ Bank! Choose your options for today!");
System.out.println("To Deposit Press 1");
System.out.println("To Withdraw Press 2");
System.out.println("To Talk To a Representative Press 3");
} else {
System.out.println("Wrong Pin") ;
}
{
int enter1 = 1;
enter1=scr.nextInt();
if(enter1==1) {
System.out.println("Deposit");
}else if (enter1==2)
System.out.println("Enter Withdraw Amount");
else if(enter1==3)
System.out.println("Hello! My name is Kismat. How may I help you today?");
else
System.out.println("Error. Please Enter Correct Code");
int withdraw = scr.nextInt();
int creditBalance=1000;
if (withdraw<=1000){
System.out.println("Cashing Out");
}else if(withdraw<=1200){
System.out.println("Insufficient Funds. Proceed and Overdraft Charges Will Appy - (For upto $200 above Credit Balance in Checking Account)");
}else{
System.out.println("Transaction Incomplete. Insufficient Funds");
}
}
}
}
I think it would help you to restructure and break your code up a bit into methods to understand what you should be doing.
at a high level this is kind of what you need:
if(validatePin(getPin()) {
printMenu();
while(true) { //loop forever
int input = getUserSelection();
if(input == 1) {
handleDeposit();
break;
}
else if(input == 2) {
handleWithdrawal();
break;
}
else if(input == 3) {
handleRepresentative();
break;
}
else {
handleInputError();
}
else {
handlePinError();
}
If you implement each method you can start to work out the logic and it won't be so difficult to understand what you need to do.
Also excuse the formatting it was hard to type on here..

Why doesn't my Scanner work with 2 different if statements?

New to Java here. I made the following simple code that asks the user to choose between option 1 or 2. If the selected option is 1, then it should print "You said hi", which it works well, also if selected option is 2, it should prints "you said goodbye" which it doesn't, Am I missing something here? Maybe the If statement is wrong?
the Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
if (input.nextInt() == 1) {
System.out.println("You said hi");
} else if (input.nextInt() == 2) {
System.out.println("you said goodbye");
}
}
Every time you call nextInt() it stops to wait for an int. Here you want to compare a single int from the user with one or two. Save the int you get from the user. Like,
int v = input.nextInt();
if (v == 1) {
System.out.println("You said hi");
} else if (v == 2) {
System.out.println("you said goodbye");
}
Every time you call nextInt() on your scanner, input is being consumed. So in your case, when the else if condition is checked, the next input is consumed, not the previous one compared. You need to cache your scanner's state:
int answer = input.nextInt();
if (answer == 1) {
System.out.println("You said hi");
} else if (answer == 2) {
System.out.println("you said goodbye")
}
For your specific case, converting to a switch statement would be another option, which evaluates its operand only once:
switch (input.nextInt()) {
case 1:
System.out.println("You said hi");
break;
case 2:
System.out.println("you said goodbye")
break;
}
Every call to input.nextInt() will wait for the new key from input(here it is the user input).
the input.nextInt() == 1 will wait for the user input.
If it is validates to true, the thread will successfully execute System.out.println("You said hi").
Else if it validates to false, it will execute the condition in the input.nextInt() ==2 where the thread will keep waiting for the next input from the user because of the input.nextInt().
If you wish to get input from user only once, execute input.nextInt() only once and store it in a variable and run cases against it. Like,
// input from user
int selection = input.getInt();
if (selection == 1) {
System.out.println("the user entered 1");
}
else if (selection == 2) {
System.out.println("the user entered 2");
}
Please get input first then check it. (Don't get input in condition statement).
Your edited code is as follows:
Added one line (int selectedOption = input.nextInt())
edit condition statement (selectedOption == 1 and selectedOption == 2)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
//Get input
int selectedOption = input.nextInt() ;
//Check
if (selectedOption == 1) {
System.out.println("You said hi");
} else if (selectedOption == 2) {
System.out.println("you said goodbye");
}
}

Trouble appropriately constructing do while loops with correct conditions to run

I am struggling to correctly loop the code I have written to convert integers to roman numerals.
I have tried implementing a do while loop to run the code starting at "please enter an integer" and ending after my switch statement with the while part being: while(case "y" || "Y" == true )
Any help would be greatly appreciated. I have been searching through previous posts on stack overflow for a couple hours now and haven't been able to find anything that helps.
public class project8
{
/**
* Constructor for objects of class Project4
*/
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if (input < 0 || input > 3999){
System.out.println("Sorry, this number is outside the range.");
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
String userInput = in.next();
switch (userInput) {
case "N":
case "n":
System.exit(0);
break;
case "Y":
case "y":
break;
}
}
else if (input > 0 && input < 3999);
{ System.out.println(Conversion.Convert(input));
}
}
}
1) Your if - else if conditions are redundant. You can use a simple if - else as input can only be in that range or not. else if makes only sence if you had two or more ranges to check, e.g.
if(input > 0 && input < 3999){
...
}
else if (input > 4000 && input < 8000){
...
}
else {
...
}
2) You don't need a switch block instead use the user input in your while condition as you want to continue looping when user input is Y/y, i.e while(userChoice.equals("Y"))
3) Use a do - while loop as you want that your application to run at least on time
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
String choice;
do{
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if(input > 0 && input < 3999){
System.out.println(Conversion.Convert(input));
}
else{
System.out.println("Sorry, this number is outside the range.");
}
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
choice = in.next();
}while(choice.equals("Y") || choice.equals("y"));
}

How to return to main menu when exit is inputted

I want to return to main menu aka "eventSelection" if 4 (exit) is selected. Right now I have it as return which exits whole program.
import java.util.*;
public class SchedulingProgram {
public static void main (String [] args) {
eventSelection();
}
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit = 4. \nINPUT : ");
int actionSelect = sc.nextInt();
if (actionSelect >= 1 && actionSelect <= 4) {
if (actionSelect == 1) {
addEvent();
} else if (actionSelect == 2) {
displayEvent();
} else if (actionSelect == 3) {
printAlert();
} else if (actionSelect == 4) {
return;
}
} else {
System.out.println("Error : Choice " + actionSelect + " Does Not Exist.");
}
}
I used to play with these kind of things too when I first started learning Java.
The most simple solution is indeed a while-loop. It evaluates the boolean expression and keeps executing the code within its brackets for as long as the boolean equals 'true'.
I refactored your example:
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
int actionSelect = 0;
while (actionSelect != 4) {
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit program = 4. \nINPUT : ");
actionSelect = sc.nextInt();
switch (actionSelect) {
case 1:
addEvent();
break;
case 2:
displayEvent();
break;
case 3:
printAlert();
break;
default:
break;
}
}
System.out.println("Exited program");
}
It will now display your menu everytime a number is entered. Except when they enter 4, which now becomes the exit out of your entire program.
When faced with multiple if-else, it's perhaps better to use a switch-case. It takes a parameter and per case, you can define the action.
If the entered parameter doesn't match a case, it falls back to the default (in this case, it does nothing and the program will continue, showing the select menu anyway)
The 'break' keyword is needed to contain the cases. Otherwise, the next line of code would be executed as well. A bit more information about the switch statement can be found here.
And ofcourse, here's the link to the while-loops.
One last tip... As I learned to program, I found that there's nothing more important than to (re)search as much as I could on Google. There are examples aplenty out there.

Syntax error on token "else", delete this [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I keep on getting this error and I tried mixing it around. But then when I choose the option, it does the option, but then said "you did not enter 1, 2 or 3".
This is the the full code. How to fix it?
The error is at
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
This is an incorrect syntax:
}else{
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
Just do it this way:
else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
The problem is in the code you provided on your paste bin.
You use two else statements, so Java complains as it doesn't know which to go to after the initial if statement.
You need to enter in another conditional statement using else if, then else. For example:
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
etc
}else if (nothing entered) {
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
}
You also have another major problem with your code. You declare the variable option and set it in an if statement, so it only has scope within that if statement. You then come out of the if statement and declare a brand new option variable before the code I provided above. This will not function, as the option integer has no value.
Instead, you need to declare your initial option int outside of your if statement, like so:
int number;
int password = 7123;
int amount = 4000;
int option;
if (number == password) {
etc...
option = userInput.nextInt();
}
Furthermore, you come out of the if statement checking the entered number against the stored password to take input on withdrawing cash etc. This is no good. It means that after the if statement checking number against password is finished, it will automatically proceed to the next block of code.
As the scanner object hasn't been created, the first three if statements will come back false and your else statement will be printed (regardless of whether the input password was correct).
Therefore, I would advise you to put that check in a separare else statement and use a while loop to confirm a correct selection ahs been entered. For example:
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
int option;
number = userInput.nextInt();
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
while (option != 1 || option != 2 || option != 3) {
System.out.println("You didn't enter a valid number. Try again");
option = userInput.nextInt();
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
else if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
else if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}
}
else
System.out.println("The Pin You Entered Was Wrong");
}
your second else statement does not close no if statement.
Also, the option variable is not in the right scope:
try this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome To Harry's Bank");
//Pin System
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
number = userInput.nextInt();
int option;
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
}else{
System.out.println("The Pin You Entered Was Wrong");
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}else{
System.out.println("You did not enter 1, 2 or 3");
}
}
}
The problem is that you the 'else' statement twice in your if-else construct.
You have:
if { }
else { }
else { }
But you probably want:
if { }
else if { }
else { }
You cannot have TWO else in a if-else case.
Your nested If statement is not proper. Use it as below
if (number == password) {
.....
.....
if (option == 1) {
}
else if (option == 2) {
}
else if (option == 3) {
} else {
System.out.println("You did not enter 1, 2 or 3");
}
} else {
System.out.println("The Pin You Entered Was Wrong");
}
You can't have two else blocks added to an if
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
Either drop one or club the two println()s into one else block
} else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
Take a look at how to use the if-then and if-then-else statements.
Alternatively, I suggest you to make use of the Switch statements for better clarity of code.
switch (option) {
case 1: Option_1 OptionOne = new Option_1();
OptionOne.Withdraw();
break;
case 2: Option_2 OptionTwo = new Option_2();
OptionTwo.Withdraw();
break;
case 3: Option_3 OptionThree = new Option_3();
OptionThree.Withdraw();
break;
default: System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}

Categories

Resources