do while loop prompting user for some input - java

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].*");
}
}

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!

For two integer user inputs, how to detect that a string has been passed on the very first input?

This is my code. A program to check for prime numbers between user inputs, 'start' and 'stop'.
import java.util.*;
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter start: ");
String start = sc.nextLine();
if(start.equalsIgnoreCase("stop"))
{
break;
}
System.out.println("Enter stop: ");
String stop = sc.nextLine();
if(stop.equalsIgnoreCase("stop"))
{
break;
}
try
{
int s1 = Integer.parseInt(start);
try
{
int s2 = Integer.parseInt(stop);
for(int i = s1; i<=s2;i++)
{
if(p1.isPrime(i))
{
System.out.print(i+" ");
}
}
System.out.println("");
}
catch(java.lang.NumberFormatException er)
{
System.out.println("Invalid Input");
}
}
catch(java.lang.NumberFormatException er1)
{
System.out.println("Invalid Input");
}
}
}
}
When taking start input, if I enter any string, I want the code to instantly detect NumberFormatException and ask for the same input again.
What happens instead, is that, it takes both inputs, whether string and integer, and only then evaluates whether it's a string.
I don't use sc.nextLine() because I want the stop functionality. I want the program to stop execution if I input "stop" anywhere.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int start = -1;
int stop = -1;
while (true)
{
if (start == -1)
{
System.out.println("Enter start: ");
if (sc.hasNextInt())
{
start = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
if (stop == -1)
{
System.out.println("Enter stop: ");
if (sc.hasNextInt())
{
stop = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
for (int i = start; i <= stop; i++)
{
// Prime number method call here
System.out.print(i + " ");
}
System.out.println();
start = stop = -1;
}
}

Getting IllegalStateException in my program?

Stacktrace Here
import java.util.*;
public class AccountClient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean infiniteLoop = true;
boolean invalidInput;
int id;
// Create array of different accounts
Account[] accountArray = new Account[10];
//Initialize each account array with its own unique id and a starting account balance of $100
for (int i = 0; i < accountArray.length; i++) {
accountArray[i] = new Account(i, 100);
}
do {
try {
//inner loop to detect invalid Input
do {
invalidInput = false;
System.out.print("Enter an id: ");
id = input.nextInt();
if (id < 0 || id > 9) {
System.out.println("Try again. Id not registered in system. Please enter an id between 0 and 9 (inclusive).");
invalidInput = true;
input.nextLine();
}
} while (invalidInput);
boolean exit;
do {
exit = false;
boolean notAnOption;
int choice;
do {
notAnOption = false;
System.out.print("\nMain Menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
choice = input.nextInt();
if (choice < 1 || choice > 4) {
System.out.println("Sorry, " + choice + " is not an option. Please try again and enter a number between 1 and 4 (inclusive).");
notAnOption = true;
}
} while(notAnOption);
switch (choice) {
case 1: System.out.println("The balance for your account is $" + accountArray[id].getBalance());
break;
case 2: {
boolean withdrawFlag;
do {
System.out.print("Enter the amount you would like to withdraw: ");
double withdrawAmount = input.nextInt();
if (withdrawAmount > accountArray[id].getBalance()) {
System.out.println("Sorry, you only have an account balance of $" + accountArray[id].getBalance() + ". Please try again and enter a number at or below this amount.");
withdrawFlag = true;
}
else {
accountArray[id].withdraw(withdrawAmount);
System.out.println("Thank you. Your withdraw has been completed.");
withdrawFlag = false;
}
} while (withdrawFlag);
}
break;
case 3: {
System.out.print("Enter the amount you would like to deposit: ");
double depositAmount = input.nextInt();
accountArray[id].deposit(depositAmount);
System.out.println("Thank you. You have successfully deposited $" + depositAmount + " into your account.");
}
break;
case 4: {
System.out.println("returning to the login screen...\n");
exit = true;
}
break;
}
} while (exit == false);
}
catch (InputMismatchException ex) {
System.out.println("Sorry, invalid input. Please enter a number, no letters or symbols.");
}
finally {
input.close();
}
} while (infiniteLoop);
}
}
The exception code:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1465)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at playground.test.main.Main.main(Main.java:47)
Hello, I made a basic program that uses a class called account to simulate an ATM machine. I wanted to throw an exception if the user didn't type in a letter. This worked fine, however I needed to make it loop so the program didn't terminate after it threw the exception. To do this I just put the try catch in the do while loop I had previously. When I did this though, it's throwing an IllegalStateException every time I type in a letter or choose to exit an inner loop I have which takes the user back to the loop of asking them to enter their id. What is an IllegalStateException, what is causing it in my case, and how would I fix this? Thanks.
It's fairly simple, after you catch the exception the finally clause gets executed. Unfortunately you're closing the scanner within this clause and Scanner.close() closes the underlying input stream (System.in in this case).
The standard input stream System.in once closed can't be opened again.
To fix this you have to omit the finally clause and close the scanner when your program needs to terminate and not earlier.

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.

while() loop for user input

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");
}
}
}

Categories

Resources