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.
Related
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.
Keep getting syntax error, insert while expression to complete do statement. It maybe something simple like curly brackets etc.
{
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
} while (inputOk != true);
s.close();
System.out.println("Thank you");
}
In your code you are missing ending curly brackets "}" for do. For Scanner it's better to use try with resource. here is working code
int num = 0;
//flag
boolean inputOk = false;
try (Scanner s = new Scanner(System.in)) {
do {
try {
System.out.println("Enter a number....");
num = s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
}
while (inputOk != true);
}
System.out.println("Thank you");
You are missing ending curly brackets "{" of Do I have corrected it in below code
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}} while (inputOk != true);
{
s.close();
System.out.println("Thank you");
}
Hopeing someone can help. Been trawling for days and cant find a solution. Trying to create a while loop with a try/throw/catch for exception handling, but need to catch multiple exceptions.
I've tried just about everything I can think of it either doesn't come out the loop or it skips the rest of the code (not pasted here) and finishes the program.
Scanner scanner = new Scanner(System.in);
boolean NotCorrectInput = false;
howManyToAdd = 0;
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
NotCorrectInput = true;
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
try {
if (howManyToAdd < 1) {
throw new NegativeArraySizeException();
}
}
catch (NegativeArraySizeException e) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
SecondProduct lp[] = new SecondProduct[howManyToAdd];
//Rest of code from here on down.
I would like it to expect an int but if it is passed a double or a float then it will handle that in the loop and keep going until it is passed an int, but also if it is given a negative number to start off the array then it will loop back to the start and ask for a positive int to be passed.
You don't need to throw any exception :
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
if (howManyToAdd >= 1)
NotCorrectInput = true;
else
System.err.println("You have not entered a positive number. Please try again.");
}
catch (InputMismatchException e) {
System.err.println("You have not entered the correct number format. Please try again.");
scanner.next();
}
}
BTW, NotCorrectInput is a confusing name, since you actually set it to true when the input is correct.
while (!NotCorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
NotCorrectInput = true;
if (howManyToAdd < 1) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
}
Thats how you do multiple try catch!
Just adjust your code a bit:
Scanner scanner = new Scanner(System.in);
boolean CorrectInput = false;
howManyToAdd = 0;
while (!CorrectInput) {
try {
System.out.println("How many products would you like to add?");
howManyToAdd = scanner.nextInt();
if (howManyToAdd < 1) {
throw new NegativeArraySizeException();
}
else
CorrectInput = true;
}
catch (InputMismatchException e){
System.err.println("You have not entered the correct number format. Please try again.");
}
catch (NegativeArraySizeException e) {
System.err.println("You have not entered a possitive number. Please try again.");
}
}
do {
try {
System.out.println("how many times");
stringy = scanner.next();
rollnumber = Integer.parseInt(stringy);
if (stringy.equals("q")){
System.exit(0);
}
nigh = 2;
} catch (Exception e) {
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (nigh == 1);
I'm not sure what I'm doing wrong. Its supposed to read the string but it still obviously doesn't register it in the system.exit. Please explain to me and examples would be very nice! thanks!
It will never reach the condition that checks for "q", since it will get an exception in parseInt.
If you type "q", parseInt would throw NumberFormatException before your condition that checks for "q".
You should move your rollnumber= Integer.parseInt(stringy); line to be after the condition.
My suggestion (without the System.exit()) :
boolean quit = false;
do {
try {
System.out.println("how many times");
stringy= scanner.next();
if (stringy.equals("q")) {
quit = true;
} else {
rollnumber= Integer.parseInt(stringy);
}
}
catch (Exception e)
{
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (!quit);
Try this:
do {
try {
System.out.println("how many times");
stringy = scanner.next();
if (stringy.equals("q")){
System.exit(0);
}
rollnumber = Integer.parseInt(stringy);
nigh = 2;
}catch (Exception e) {
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (nigh == 1);
I think you are not going out of the while-loop when you try to exit your app. Maybe you can try and add a return statement in the if after you try to exit your app.
*EDIT: Okay after fixing the try catch error I get a problem in the catch {.. when it prints.
*, Basically when I say I want to play again it continues the game as it should but it also prints the first catch and then asks for an input at line 23.
if (decision.equalsIgnoreCase("yes"))
{
ai = (int)(Math.random()*101);
System.out.println("From 0 to 100, what number do you think I have generated?");
tryCatch = true;
loop = true;
rtrn = true;
while (tryCatch == true)
{
while (loop == true)
{
try
{
guess = Integer.parseInt(iConsole.nextLine());
if (guess >= 0)
{
loop = false;
}
}
catch (NumberFormatException e)
{
System.out.println("Invalid input. Please try again.");
}
catch (InputMismatchException e)
{
System.out.println("Invalid input. Please try again!");
}
}
Hi this is my first post so if I get the code formatting on the forum wrong I'll edit it.
Right now I'm coding a game in java eclipse where the cpu generates a number and the user has to guess it. I am using the scanner class for most of this. What I am having trouble doing is creating a try catch to check the user input if it is a valid Integer.
What ends up happening is that the code block below it doesn't recognize the already-initialized variable.
package ics3U;
import java.util.*;
import java.io.*;
public class highLow
{
static public void main (String args[]) throws IOException
{
String name;
String decision;
String decision2;
int ai;
int guess;
int counter = 1;
boolean fullGame = true;
boolean tryCatch = true;
boolean rtrn = true;
Scanner iConsole = new Scanner(System.in);
System.out.println("Hello! Welcome to HiLo!");
System.out.println("What is your full name?");
name = iConsole.nextLine();
System.out.println("Hello " + name + "! Would you like to play?");
decision = iConsole.nextLine();
while (fullGame == true)
{
if (decision.equalsIgnoreCase("yes"))
{
ai = (int)(Math.random()*101);
System.out.println("From 0 to 100, what number do you think I have generated?");
tryCatch = true;
rtrn = true;
while (tryCatch == true)
{
try
{
guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
}
while (guess != ai)
{
if (guess < ai)
{
System.out.println("Too low!");
guess = iConsole.nextInt();
}
else if (guess > ai)
{
System.out.println("Too high!");
guess = iConsole.nextInt();
}
counter = counter + 1;
}
System.out.println("Correct! You guessed it after " + counter + " tries!");
counter = ((counter - counter)+1);
System.out.println("Would you like to play again?");
while (rtrn == true)
{
decision2 = iConsole.next(); //finally..
if (decision2.equalsIgnoreCase("yes"))
{
fullGame = true;
tryCatch = false;
rtrn = false;
break; //do-while may be needed, have to bypass catch, 'break' works after restating value of tryCatch & rtrn
}
else if (decision2.equalsIgnoreCase("no"))
{
System.out.println("Goodbye.");
fullGame = false;
tryCatch = false;
rtrn = false;
iConsole.close();
}
else
{
System.out.println("Sorry?");
}
}
/*catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
}
catch (NumberFormatException e)
{
System.out.println("Invalid input. Please try again.");
}
//More specific Exceptions, turn this on later
catch (InputMismatchException e)
{
System.out.println("Invalid input. Please try again!");
}*/
}
}
else if (decision.equalsIgnoreCase("no"))
{
System.out.println("Goodbye.");
fullGame = false;
tryCatch = false;
rtrn = false;
iConsole.close();
}
else
{
System.out.println("Sorry?");
decision = iConsole.nextLine();
}
}
}
}
Add a continue statement in your catch block. That way, if the user enters something that's not an integer and parsing fails, it will immediately try again rather than trying to run the rest of the loop.
try
{
guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
continue; // jump to beginning of loop
}
Try moving all your code after the catch block (in the loop) inside the try block after this line
guess = Integer.parseInt(iConsole.nextLine());
As you currently have it, anytime there is an exception in the parseInt, it will still try to process the unassigned guess instead of restarting the loop.
Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,
int guess = -1; // some default value
You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.
boolean validGuess = false;
while (!validGuess) {
// prompt user for input here
try {
guess = Integer.parseInt(iConsole.nextLine());
if (/* .... test if guess is valid int */ ) {
validGuess = true;
}
} catch (NumberFormatException e) {
// notify user of bad input, that he should try again
}
}
You could even encapsulate all of this into its own method if you need to do similar things throughout the program.