while() loop for user input - java

I'm working on setting up a while() that executes until the user enters an integer. However, the way I have it now, the loop prints the message "Please enter an integer" again after the integer has been entered, and then the program executes normally. Can someone suggest a way to make not print that message again after an integer has been entered? Thanks!
System.out.println("Enter word length");
if(in.hasNextInt())
{
n = in.nextInt();
}
else
{
while(in.hasNext()) //this is the loop i'm talking about
{
System.out.println("Please enter an integer");
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
}
}
}

I am assuming that you want user to enter int (or Integer) and repeatedly ask user until user enters int(or Integer). If so, try this:
System.out.println("Enter word length");
if(in.hasNextInt()) {
n = in.nextInt();
} else {
while(in.hasNext()) //this is the loop i'm talking about
{
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
System.out.println("Please enter an integer");
}
}
}

Related

how to check the else statement in if else condition

package react;
import java.util.Scanner;
public class Intputfromuser {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter a number to compare with number 5 ");
Scanner input= new Scanner(System.in);
int a=input.nextInt();
if(a==2)
{
System.out.println("U Have Entered The same value");
}
else if(a<2)
{
System.out.println("Ur number is Smaller than 2");
}
else if(a>2)
{
System.out.println("U Have Entered the number Greater than ");
}
else {
System.out.println("U Have Enterer Invalid Input");
}
}
}
how to get only integer from the user if the user enters any thing except integer then else statement should run
Another alternative. Be sure to read the comments in code:
public static void main(String[] args) {
/* Open a keyboard input stream. There is no need to close
this stream. The JVM will do that automatically when the
application closes. */
Scanner input = new Scanner(System.in);
String val = ""; // Used to store User input:
// User Prompt with 'quit' capability and entry validation:
while (val.isEmpty()) {
System.out.print("Enter a number to compare with number 5 (q to quit): -> ");
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was 'q' for quit supplied?
if (val.equalsIgnoreCase("q")) {
/* Yes...then quit. Returning out of main() effectively
closes this particular application: */
System.out.println("Quiting - Bye Bye");
return;
}
// Validate Entry:
/* Is entry a string representation of a signed or unsigned Integer
value and does the supplied value fall within the relm of an int? */
if (!val.matches("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) ||
(Long.parseLong(val) > Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println("Invalid Numerical Entry! {" + val + ") Try again..."
+ System.lineSeparator());
val = ""; // Empty variable to ensure re-loop:
}
}
// If you make it to this point in code, the User input was valid!
// Now parse the String numerical value to an int:
int a = Integer.parseInt(val);
/* At this point, there are only three usable conditions:
Equal To, Less Than, and Greater Than (validity has
already been handled within the `while` loop: */
// Equal To:
if (a == 5) {
System.out.println("You have entered The same value.");
}
// Less Than:
else if (a < 5) {
System.out.println("Your number is smaller than 5.");
}
// Greater Than:
else {
System.out.println("You have entered a number greater than 5.");
}
// DONE
}
You can also create method to collect input and make it inside loop like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("enter a number to compare with number 5: ");
int userInput = getInteger();
if (userInput == 2)
{
System.out.println("U Have Entered The same value");
}
else if (userInput < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else {
System.out.println("U Have Entered the number Greater than 2");
}
}
static int getInteger() {
boolean correct = false;
Scanner input = new Scanner(System.in);
int userInput = 0;
do {
try {
userInput = input.nextInt();
correct = true;
} catch (Exception e) {
System.out.println("Incorrect input");
System.out.println("Please try again: ");
} finally {
input.nextLine();
}
}
while (!correct);
input.close();
return userInput;
}
}
Important note with scanner.nextInt() or scanner.nextDouble()
you need to call scanner.nextLine() after that to clear input. Otherwise you will end up with endless loop.
Use input.nextLine() instead and parse it to a String.
To avoid a ParseException, surround it by using a try { ... } catch() { ... } block.
In the catch block you can e.g. print a message informing the user of the wrong input.
public static void main(String[] args) {
System.out.println("enter a number to compare with number 5 ");
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
try {
int option = Integer.parseInt(userInput);
if (option == 2)
{
System.out.println("U Have Entered The same value");
}
else if (option < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else if (option > 2)
{
System.out.println("U Have Entered the number Greater than 2");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
Hope this sort of helped!

do while loop prompting user for some input

I'm new to do while loops.
I've attempted to create a do-while loop that checks if the users input is an integer or the character x. If it is neither it prompts the user to try again.
The loop instead prompts the user twice:
Intended output:
Enter answer:
500
//program is succesful
Actual output:
Enter answer:
500
//prompts user for more input
Code:
do {
System.out.println("Enter answer: ");
input = scan.next();
if(input.trim().equals("x"))
{
terminate = false;
break;
}
while (!scan.hasNextInt()) {
input = scan.next();
System.out.println(input + " is not a interger!!");
}
operationResult = scan.nextInt();
valid = false;
} while (valid);
You could always use a try...catch but I think this will be better -
do{
if(scan.hasNextInt()){
operationResult = scan.nextInt();
break;
}else if(scan.next().trim().equals("x")){
break;
}else{
System.out.println("Enter an Integer!!");
}
}while(true);
It checks whether its an integer first, so there's no need of a try...catch
You can use as given below:
It will not check for integer value, however it will check for numeric value entered, may this will help
public class SomeClass {
public static void main(String args[]) {
try (Scanner scan = new Scanner(System.in)) {
do {
String str = scan.next();
if (isNumeric(str)) {
System.out.println("Program Ends");
break;
} else if (str.equalsIgnoreCase("x")) {
System.out.println("Program Ends");
break;
} else {
System.out.println("Enter Again");
}
} while (true);
}
}
public static boolean isNumeric(String str) {
return !str.matches(".*[^0-9].*");
}
}

Object not Being Initialized Due to Scope

Apologies for the long code I'm about to include. What I'm trying to do is save certain validated, user input variables to an object. I believe my issue is due to the variables scope, that's why I'm having the error customerAccount may not have been initialized.
If anybody could point me in the right direction, it'd be greatly appreciated.
import java.util.*;
import java.io.*;
public class ATM {
public void run() {
// USED FOR DEBUGGING PURPOSES. SET TO TRUE TO ENABLE DEBUGGING MODE
boolean debug = false, mainCheck = false, check = false;
Scanner input = new Scanner(System.in);
Scanner fInput = null;
int idNumber = 0;
String lastName, firstName, emailAddress, phoneNumber;
double startingBalance;
Client customerAccount;
File file = new File("accountData.txt");
if(!file.exists()) {
System.out.println("File does not exist within directory. Creating file now.");
PrintWriter output = null;
try {
output = new PrintWriter(file);
}
catch(IOException e) {
System.out.println("Something went wrong during file creation.");
}
finally {
if (output != null)
output.close();
}
}
ArrayList<Client> clientArr = new ArrayList<Client>();
try {
fInput = new Scanner(new File("accountData.txt"));
}
catch(Exception e) {
System.out.println("ERROR: File Not Found.");
e.printStackTrace();
}
while(fInput.hasNext()) {
try{
int tempID = fInput.nextInt();
String tempFName = fInput.next();
String tempLName = fInput.next();
String tempPNumber = fInput.next();
String tempEmail = fInput.next();
double tempBalance = fInput.nextFloat();
Client tempClient = new Client(tempID, tempFName, tempLName, tempPNumber, tempEmail, tempBalance);
tempClient.getAccount().setID(tempID);
clientArr.add(tempClient);
if(debug == true)
System.out.println(tempID+" "+tempFName+" "+tempLName+" "+tempPNumber+" "+tempEmail+" $"+tempBalance);
}
catch(NoSuchElementException e) {
System.out.println("ERROR: Missing a required data field.");
}
}
if(debug == true)
System.out.println(clientArr.size());
int menuChoice = 0;
while(menuChoice != 5) {
System.out.println("**********************************");
System.out.println("Thank you for choosing Java World Bank!");
System.out.println("Main Menu: ");
System.out.println("[1] Login as an existing user.");
System.out.println("[2] Display client list sorted by last name.");
System.out.println("[3] Display client list sorted by account number.");
System.out.println("[4] Create a new client.");
System.out.println("[5] Exit.");
System.out.println("====================================");
do {
try {
System.out.println("Enter your choice: ");
menuChoice = input.nextInt();
mainCheck = true;
}
// Checks if user enters an unexpected input (not a digit)
catch(InputMismatchException e) {
System.out.println("Invalid input! Please use a numeric value between 1 and 5.");
if(debug == true)
e.printStackTrace();
input.nextLine();
}
}while(!mainCheck);
switch(menuChoice) {
case 1:
System.out.println("Please enter your fist name: ");
input.nextLine();
String loginFName = input.nextLine();
while(loginFName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. First name needs to be all letters. Please try again.");
loginFName = input.nextLine();
}
System.out.println("Please enter your last name: ");
String loginLName = input.nextLine();
while(loginLName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. Last name needs to be all letters. Please try again.");
loginLName = input.nextLine();
}
final String searchFName = loginFName;
final String searchLName = loginLName;
int loginValidation = 0;
Optional<Client> queryResult = clientArr.stream().filter(value -> value.getFName().equals(searchFName)
&&value.getLName().equals(searchLName)).findFirst();
if(queryResult.isPresent()) {
System.out.println("User "+loginFName+" "+loginLName+" successfully logged into. Welcome back to Java World Bank.");
menuChoice = 5;
}
else
System.out.println("Login failed. Returning to main menu.");
break;
case 2:
System.out.println("Clients of Java World Bank, sorted by last name: ");
clientArr.sort( (p1, p2) -> p1.getLName().compareTo(p2.getLName()) );
for(Client client : clientArr)
System.out.println(client);
menuChoice = 5;
break;
case 3:
System.out.println("Clients of Java World Bank, sorted by ID: ");
clientArr.sort( (p1, p2) -> Integer.compare(p1.getAccount().getID(),
p2.getAccount().getID()));
for(Client client : clientArr)
System.out.println(client);
menuChoice = 5;
break;
case 4:
System.out.println("You are now creating a new client account with Java World Bank!");
System.out.println("Some information is required to create this account.");
System.out.println("What would you like your ID number to be? It must contain only integers.");
check = false;
do {
try {
System.out.println("Please enter your choice: ");
idNumber = input.nextInt();
check = true;
}
catch(InputMismatchException e) {
System.out.println("ERROR: ID must contain integers only!");
input.nextLine();
}
}while(!check);
startingBalance = 0;
check = false;
// Continiously prompts user to enter valid input
do {
try {
System.out.println("What will be your starting balance?");
startingBalance = input.nextDouble();
check = true;
}
// Checks if user enters a value that is not a double
catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a numeric value.");
input.nextLine();
if(debug == true)
e.printStackTrace();
}
}while(!check);
customerAccount = new Client(idNumber, startingBalance);
System.out.println("Please enter client's first name: ");
firstName = input.nextLine();
customerAccount.setFName(firstName);
// Verifies first name is only letters, either capital or lowercase
while(firstName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. First name needs to be all letters. Please try again.");
firstName = input.nextLine();
customerAccount.setFName(firstName);
}
System.out.println("Please enter client's last name: ");
lastName = input.nextLine();
customerAccount.setLName(lastName);
// Verifies last name is only letters, either capital or lowercase
while(lastName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. Last name needs to be all letters. Please try again.");
lastName = input.nextLine();
customerAccount.setLName(lastName);
}
System.out.println("Please enter client's email address: ");
emailAddress = input.nextLine();
customerAccount.setEmail(emailAddress);
// Verifies email address only uses lowercase/capital letters, dot, underscore, and/or dashes followed by # symbol to specify domain
while(emailAddress.matches("^[A-Za-z0-9+_.-]+#(.+)$") == false) {
System.out.println("Invalid input. Email not in valid format. Please try again.");
emailAddress = input.nextLine();
customerAccount.setEmail(emailAddress);
}
System.out.println("Please enter client's phone number: ");
phoneNumber = input.nextLine();
// Verifies phone number follows valid North American format 000-000-0000
while(phoneNumber.matches("[0-9]\\d{2}-[0-9]\\d{2}-\\d{4}") == false) {
System.out.println("Invalid input. Phone number must be in the following format: 123-456-7890. Please try again.");
phoneNumber = input.nextLine();
customerAccount.setPNumber(phoneNumber);
}
// Verifies that the starting balance the user inputs is positive
while(startingBalance < 0) {
System.out.println("**********************************");
System.out.println("ERROR: You can not start with a negative balance.");
System.out.println("Please enter a POSITIVE value for your starting balance: ");
startingBalance = input.nextDouble();
}
}//end switch
}
// Debugging to verify user input is correctly stored
if(debug == true) {
System.out.println(customerAccount.toString());
Account testing = customerAccount.getAccount();
System.out.println("ID: "+testing.getID()+ " Balance: "+testing.getBalance());
}
System.out.println("********************************");
System.out.println("Your account has been fully initialized! Thank you for choosing Java World Bank!");
System.out.println("********************************");
// Loops through menu prompt until user enters 4 to quit
int choice = 0;
while(choice != 4) {
System.out.println("Client Menu");
System.out.println("[1] Check Balance");
System.out.println("[2] Withdraw");
System.out.println("[3] Deposit");
System.out.println("[4] Exit");
System.out.println("=================================");
// Continiously prompts user to enter valid input
check = false;
do {
try {
System.out.println("So... What do you want to do?");
choice = input.nextInt();
check = true;
}
// Checks if user enters an unexpected input (not a digit)
catch(InputMismatchException e) {
System.out.println("Invalid input! Please use a numeric value between 1 and 4.");
if(debug == true)
e.printStackTrace();
input.nextLine();
}
}while(!check);
double amount = 0;
switch(choice) {
// Will display updated balance
case 1:
System.out.println("Your current balance is: $"+customerAccount.getAccount().getBalance());
System.out.println("********************************");
break;
// Allows user to withdraw money from current balance
case 2:
// Continiously prompts user to enter valid input
check = false;
do {
try {
System.out.println("How much do you wish to withdraw?");
amount = input.nextDouble();
customerAccount.getAccount().withdraw(amount); // Passes withdraw value to Account class
System.out.println("********************************");
check = true;
}
// Validates that customer has enough money to withdraw the specified amount
catch(OutOfMoney error) {
System.out.println("You do not have enough funds to do this.");
System.out.println("********************************");
}
// Validates that customer enters expected input
catch(InputMismatchException e) {
System.out.println("INVALID INPUT. Please enter a numeric value.");
// Used to clear input buffer after catching exception
input.nextLine();
System.out.println("********************************");
}
}while(!check);
// Debugging to make sure values are correctly calculated
if(debug == true)
System.out.println(customerAccount.getAccount().getBalance());
break;
// Allows user to deposit money to current balance
case 3:
check = false;
do {
try {
System.out.println("How much do you wish to deposit?");
amount = input.nextDouble();
customerAccount.getAccount().deposit(amount); // Passes deposit value to Account class
System.out.println("********************************");
check = true;
}
// Validates that user enters expected input
catch(InputMismatchException e) {
System.out.println("Invalid input. Please enter a numeric value.");
// Used to clear input buffer after catching exception
input.nextLine();
System.out.println("********************************");
}
}while(!check);
// Debugging to make sure values are correctly calculated
if(debug == true)
System.out.println(customerAccount.getAccount().getBalance());
break;
// Exits program
case 4:
System.out.println("Thank you for choosing Java World Bank!");
break;
// Checks if user does not enter 1, 2, 3, or 4 in main menu prompt
default:
System.out.println("You have entered an invalid input. Please try again.");
System.out.println("********************************");
break;
}
}
input.close();
}
}
Since the initialization of your object happens in a condition the compiler cannot figure out if it is initialized or not so you need to make sure its initialized outside a condition,for example make it null.
Client customerAccount = null ;
First, you may want to see here about declaring and initializing variables: here
You initialize the customerAccount on this line: customerAccount = new Client(idNumber, startingBalance);
However, that occurs within the switch in case 4. Then on this line System.out.println(customerAccount.toString()); you attempt to access the customerAccount's toString function. As this step is not in case 4, customerAccount may not be initialized.
Consider the case where the switch statement does not go to 4 and debug is set to true. customerAccount will be declared from this line: Client customerAccount; however, the code path will not initialize it in any way so you cannot call toString on it.
One solution could be to initialize the customerAccount to a null when you declare it or to a new Client(), or only attempt to access this variable after it was necessarily initialized. Hard to be sure without seeing the Client class.
Do note that in the null case, you may have to do some null checks, for instance, if customerAccount is null then customerAccount.toString() will throw an exception.

Scanner object does not return intended result

I am trying to use the scanner object to validate some user input. According to my requirement if user input is 100>inputs<0 I need to provide some console output. However, the following code does not work when I enter 100/0 and provides me some empty console output. I tried to test this code block with 102 and -1 with same (empty) console output
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
}else if (sc.nextInt() > 100){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else if (sc.nextInt() < 0){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else {
score = sc.nextInt();
break;
}
}
return score;
}
The error is causing because of using nextInt() in the if else block . Use the method hasNextInt() and store the value in a temporary variable before validating the value .
You should not read from the Scanner several times. Just read the number once via nextInt into the variable and check it. Otherwise on every if branch you will be prompted for a new number.
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}

How do i make the program keep looping until the user has entered an integer

i am trying to modify my program so that even when the user has entered a string instead of the program crashing it should keep looping and asking for the user to enter the exam grade which needs to be an integer, only when the user has entered an integer should the program terminate. I am referring to the code in the do-while block
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchingException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score;
String choice;
try {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
do {
if(score <40) {
System.out.println("You FAILED");
}else if(score >=40 && score <50){
System.out.println("Your grade: PASS MARK");
}else if(score >=50 && score <60) {
System.out.println("Your grade: 2:2");
}else if (score >=60 && score <70) {
System.out.println("Your grade: 2:1");
}else {
System.out.println("Your grade: 1:1");
}
System.out.println("Do you want to enter another grade: ");
choice = scan.next();
if(choice.equalsIgnoreCase("yes")) {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
System.err.println("Incorrect Input");
}
}while();
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
Use a boolean variable to keep track of whether or not to keep looping. For example:
boolean loop = true;
do {
// set loop to false when you want to end
} while(loop);
so you could do:
int score = null;
boolean isInt = false;
do {
System.out.println("Enter your percentage mark:");
try {
score = scan.nextInt();
isInt = true;
} catch (InputMismatchException e) {
//Not An Integer
isInt = false;
}
} while(false)
//Do you if statements here if it gets out of the while loop which means the user entered an int
Instead of assuming the number inputed is an int, you can input it as a String and loop until that string represents an int:
int intScore;
String score;
boolean gotInt = false;
while (!gotInt) {
score = scan.next();
try {
intScore = Integer.valueOf(score);
gotInt = true;
} catch (NumberFormatException e) {
// output some warning
}
}
Did you consider using JOptionPane to get an input from the user? It is able to display a little window with a text field and a OK and Cancel button which would fit your needs perfectly.
Here is the documentation for JOptionPane#showInputDialog:
static String showInputDialog(Component parentComponent, Object message, String title, int messageType)
Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.

Categories

Resources