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;
}
Related
I am making an atm program that takes in an account number and a pin. When I try to type in anything except the accepted accounts and pins that are predetermined, it is supposed to give an error message and the user tries again. The only problem is that it prints out the error message but moves on to the next input instead of repeating the previous input. i.e. goes from entering the account number to entering the pin number. The same thing happens for the pin as well. I really don't know what to make of it. Thanks in advance! Here's a snippet of my code:
import java.util.*;
import java.lang.*;
public class Menu {
Scanner input = new Scanner(System.in);
//Bank bank = new Bank();
boolean keepGoing = true;
public static void main(String[] args){
Menu menu = new Menu();
menu.startMenu();
}//end main
public void startMenu(){
int choice = 0;
int verify1 = 0;
int verify2 = 0;
int account = 0;
int pin = 0;
printGreet();
while(keepGoing){
System.out.print("Please enter Account number: ");
do{
try{
account = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("Error: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(account < 0 || account > 99999){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(account >= 0 && account <= 99999));//end do/while
System.out.print("Please enter PIN number: ");
do{
try{
pin = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(pin < 0 || pin > 99999){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(pin >= 0 && pin <= 99999));//end do/while
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if((verify1 == 1) && (verify2 == 1)){
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
}else if((verify1 == 2) && (verify2 == 2)){
printUserMenu();
choice = getUserChoice();
userChoices(choice);
}else{
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}//end if/else
}//end while
}//end startMenu()
The whiles only check if the account number is invalid. When a parsing error occurs the account/pin variable is still 0 so it doesn't repeat.
I fixed/improved the code for you. Note you should always debug your code before you ask a question on StackOverflow.
public void startMenu() {
int account = 0;
int pin = 0;
printGreet();
while (keepGoing) {
System.out.print("Please enter Account number: ");
boolean invalid;
do {
invalid = false;
try {
account = input.nextInt();
// Cancel if the number is invalid
if (account < 0 || account > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();
// Mark the loop iteration as invalid
invalid = true;
}
} while (invalid);
System.out.print("Please enter PIN number: ");
do {
invalid = false;
try {
pin = input.nextInt();
// Cancel if the number is invalid
if (pin < 0 || pin > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();
invalid = true;
}
} while (invalid);
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if ((verify1 == 1) && (verify2 == 1)) {
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
} else if ((verify1 == 2) && (verify2 == 2)) {
printUserMenu();
choice = getUserChoice();
userChoices(choice);
} else {
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}
}
}
So for my programming assignment the user has to enter the number of grades, but we have to check the input and return the proper error. The number has to be a positive number, and the program needs to differ between the error and give the proper response and loop it back until the right number is inputed. I got the error checking part but I'm having trouble getting the program to continue to the next part. any help would be appreciated
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
if (numGrade < 0){
System.out.println("Your number of grades needs to positive! Try again");
count1++;
continue;
}
}
else{
System.out.println("You did not enter a number! Try again");
count1++;
input.next();
continue;
}
}while (count1 > 0);
Try this,
//use a boolean to tell the loop to continue or not
boolean cont = true;
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
//I assume 0 is a valid response (not a negative int)
if (numGrade <= 0){
System.out.println("Your number of grades needs to positive! Try again");
continue;
}
else {
cont = false;
System.out.println("Your input is valid! Value entered is " + numGrade);
}
}
else {
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
}
while (cont);
I created a program which asks the user for an input (grade). I am using try/catch statements to catch InputMismatchException, in case the user enters an incorrect data type. The problem occurs during the second try/catch statement. After the program asks "Enter your percentage mark?" in the if statement and the user enters an incorrect data type. The program then reprints your grade twice and do you want to enter your grade twice.
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")) {
try{
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
}catch(InputMismatchException e) {
System.err.print("Incorrect Input");
}
}
}while(!choice.equalsIgnoreCase("No"));
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
Your catch block does not transfer control. (e.g, by returning or throwing another exception) This means that after the message is printed, the program checks the while condition. Since that condition will never be true in this situation, it will rerun the loop using the old score.
The statement that would have updated the score threw an exception, so it wasn't updated.
You need to keep on repeating asking percentage from user if user enters incorrect input data to it.
Right now, it catches exception and then enter's the do while loop and hence prints the grade once again. You might need to do the following:
do {
System.out.println("Enter your percentage mark: ");//inner one
try{
score = scan.nextInt();
}catch(InputMismatchException e) {
System.err.print("Incorrect Input");
score = -1;
}
}while(score == -1);
So you loop until score is -1 (score cant be negative in exam and hence -1). So next time when you run it with invalid input, it will catch the exception and set score as -1 and then check for while condition which will satisfy and hence will again start from do i.e. asking user to input percentage.
A note: If you input an invalid number (say a string) when you first enter score then your program will terminate after printing "Incorrect Input " onto error console.
It should be while(choice.equalsIgnoreCase("No")); and not while(!choice.equalsIgnoreCase("No"));
Fixed it! Give it a try now.
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: ");{
try{
score = scan.nextInt();
}catch(InputMismatchException e) {
System.err.print("Incorrect Input");
}
}
}while(choice.equalsIgnoreCase("No"));
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
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.
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");
}
}
}