Do...while is not working in input verification - java

So I'm trying to do an input verification for my program in java, and I'm trying to do that in this setter:
public void setClientName(String clientName) {
boolean valid;
do{
valid = false;
try{
if(clientName.matches("[a-zA-Z]+")){
this.clientName = clientName;
}else{
throw new IllegalArgumentException("Invalid client name");
}
}catch(Exception e){
System.out.println("Invalid name");
valid = true;
}
}while(!valid);
}
But when I call it and put a wrong name, the do...while does not work and the program just continue
Here's where I call it
public void openAccount(int i){
nCartao = 2021120040 + i;
System.out.println("Account Number : " + (nCartao));
System.out.println("Client Name :");
setClientName(sc.next()); // I CALL IT HERE
System.out.println("Client Age : ");
age = sc.nextInt();
System.out.println("Balance :");
balance = sc.nextInt();
}
What am I doing wrong?

Maybe that's because in your catch you are stating that valid is true when it should be false to repeat the block.

Related

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.

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

Java Exception Handling (Empty spaces in user input)

I need to create an exception class that will throw an exception when there are spaces in user input for a name, password, etc. (all strings). I have written all the code that I thought was necessary and no matter what I input, the exception is always thrown.
What am I doing wrong?
The following are snippets of code. If the whole program is needed, let me know.
EmptyInputException class:
public class EmptyInputException extends Exception{
public EmptyInputException(){
super("ERROR: Spaces entered - try again.");
}
public EmptyInputException(String npr){
super("ERROR: Spaces entered for " + npr + " - Please try again.");
}
}
Here the getInput method where I catch the exception:
public void getInput() {
boolean keepGoing = true;
System.out.print("Enter Name: ");
while (keepGoing) {
if(name.equalsIgnoreCase("Admin")){
System.exit(1);
}else
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}//end loop
}
System.out.print("Enter Room No.:");
while (keepGoing) {
if(room.equalsIgnoreCase("X123")){
System.exit(1);
}else
try {
room = scanner.next();
if (room.contains(" ")){
throw new EmptyInputException();
}else
keepGoing = false;
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
System.out.print("Enter Password:");
while (keepGoing) {
if(pwd.equals("$maTrix%TwO$")){
System.exit(1);
}else
try {
pwd = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
}
I feel like I am missing the part where the scanner input should include spaces, such as:
if(name.contains(" "))
and so on...
So far, my output (after entering a name, for example) will say, Error: Please do not put spaces.
try {
name = scanner.next();
keepGoing = false;
if(name.contains(" "))
throw new EmptyInputException();
}
Should do the trick?
Your guess was right.
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException(); // You're always going to throw an Exception here.
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
Probably careless mistake. Needs a if(name.contains(" ")):D Same thing happened for your password block.

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.

how to handle NumberFormatException in more specific way?

I want to handle NumberFormatException in more specific way.
This exception occurs, when it tries assign anything but an integer, when the following is entered:
string
character
empty input
double number
Depending on what was entered I want to display a proper message, like
you've entered string, please enter an integer
or
value can't be null, please enter an integer value
The code below catches NumberFormatException in general way.
I wonder is there a way to include more catch clauses.
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
First take the input from the user and after that try to convert it to integer.
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
String inputString = scan.next();
try {
input = Integer.parseInt();
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if(inputString.equals("") || inputString == null) {
System.out.println("empty input");
} else if(inputString.length == 1) {
System.out.println("char input");
} else {
System.out.println("string input");
}
}
}
You've to use if-else construct to specify your scenerios within catch block.
See the code below:
String inString = null;
try
{
iString = scan.next().trim();
input = Integer.parseInt(inString);
System.out.println("You've entered number: " + input);
}
catch (NumberFormatException e)
{
if(inString.equals("")
{
System.out.println("You've entered empty string.");
}
else if(inString.length() == 1)
{
System.out.println("You've entered a single char");
}
else
{
System.out.println("You've entered non-intereger number");
}
System.out.println("This caused " + e);
}
You could do some more tests on the input if parsing the input as an integer value caused an exception, something like this:
String scanned = null
try {
scanned = scan.next();
input = Integer.parseInt(scanned);
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if (scanned == null || scanned.isEmpty()) {
System.out.println("You didn't enter any value");
} else if (scanned.length() == 1)
System.out.println("You entered a single char which is not a number");
}
// and more tests, you can even try to parse as Double
}
String aString = null;
aString = scan.next().trim();
System.out.println("You've entered number: " + aString);
if("".equals(aString.trim())){
System.out.println("You have entered an Empty String");
}else if(!isNumber(aString) && aString.length()==1){
System.out.println("You have entered a Character");
}else if(!isNumber(aString) && aString.length()>1){
System.out.println("You have entered a String");
}else if(isNumber(aString)){
int input = Integer.parseInt(aString.replaceAll(",",""));
System.out.println("You have entered a correct Number"+input);
}
private boolean isNumber(String s){
return s.matches("[0-9]+(,[0-9]+)*,?");
}
public static int isInt(){
boolean ok=false;
int b=1;
do{
String next = sc.next();
int a=b;
try{
a = Integer.parseInt(next);
}catch(Exception e){
System.out.println("Invalid Option...");
continue;
}
if(a==1){b=a;ok=true;}
else if(a==2){b=a;ok=true;}
else if(a==3){b=a;ok=true;}
}while(!ok);
return b;
}

Categories

Resources