Program printing incorrectly to console - java

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

Related

Interest calculator not displaying results

I'm trying to finish this at the last minute for my Java class, when I run the program after it asks the user if the information is correct, it just loops back to the first question no matter what. Here's the code:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while(true);
}
}
What I am looking for as a sample output:
Enter number of quarters from 1 to 10
5
Enter the beginning principal balance greater than zero
4500
Enter the interest rate percentage without the percent sign, greater than 0 percent and less than/equal to 20%
3.5
You entered a principal balance of $4500.0 for 5 quarters at 3.5% interest.
Is this correct? (y/n)
y
Quarter Beginning Interest Ending
Number Balance Earned Balance
1 4500.00 39.38 4539.38
ect ect
Maybe what you ment to do is to restart the loop, if the input was wrong. In this case, you just need to switch the continue and the break.
The continue statement makes a loop immediately start the next iteration. You shoud either remove it by an empty statement ;, or negate the if-condition, remove the else and make it break on true. In addition, your code does nothing else, then getting the input and asking whether it is correct. And as it is written inside a do...while(true) loop, this loop will never end. So either remove that loop, or add an option to abort the process.
Your code should look something like the one below...
**Look out to the bottom, where the user is informed of the values entered and check for the changes made**. This is quite simple...
import java.util.Scanner;
public class correctstack{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
//Here, you give the user the opportunity to continue or re-enter the values. So you go like...
System.out.println("Is this info correct?");
String user_input = input.next();
if("y".equalsIgnoreCase(user_input) || "yes".equalsIgnoreCase(user_input)){
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "+ quarterlyEndingBalance);
System.out.println("\n\nDo you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
}
else
continue;
} while(true);
}
}

How do I catch a hasNextInt() String input exception?

In my java app, which is a simple TollMachine simulator, I must implement the try/catch code in my code. I managed to work around the String input on a hasNextInt prompt, but when I try doing the same using try/catch, I just can't get the program to go into the catch section. The program goes into an infinite loop as it is, and I really need to get it to work with the try/catch method. Otherwise, I used an if(hasNextInt)/else(workaround) to get rid of the string input and prevent the infinite loop.
public class TollMachine {
static boolean running = true; //variable to control whether the program should run
static int userInput = -1; //variable to store the user's input
static String userInput2 = ""; //variable to store the input in case user does not enter an integer
static int motoTicketCount = 0; //variable to store the number of tickets sold(moto)
static int carTicketCount = 0; //variable to store the number of tickets sold(car)
static int vanTicketCount = 0; //variable to store the number of tickets sold(van)
static int truckTicketCount = 0;//variable to store the number of tickets sold(truck)
static int totalTicketCount = 0;//variable to store the number of total tickets sold
static Scanner keyb = new Scanner(System.in); //variable to detect the user's input
public static void main(String[] args) {
while (userInput != 0) //runs while userInput != 0
{
//This is the main menu, the user is prompted to choose an option
System.out.println("1. Motorcycle");
System.out.println("2. Car");
System.out.println("3. Van");
System.out.println("4. Truck");
System.out.println("5. Display total tickets sold.");
System.out.println("0. Exit");
try {
if (keyb.hasNextInt()) //checks whether the user inputs an integer
{
userInput = keyb.nextInt(); //stores the user's input to the userInput
if (userInput > 5 || userInput < 0) //if one of these conditions are true, the user selected an option
{ //that is not mentioned
System.out.println("Invalid input."); //displays the Invalid input error
} else {
//checks which option the user chose with multiple "if" conditions
if (userInput == 1) {
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your motorcycle ticket.");
motoTicketCount++;
totalTicketCount++;
}
if (userInput == 2) {
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your car ticket.");
carTicketCount++;
totalTicketCount++;
}
if (userInput == 3) {
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your van ticket.");
vanTicketCount++;
totalTicketCount++;
}
if (userInput == 4) {
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your truck ticket.");
truckTicketCount++;
totalTicketCount++;
}
if (userInput == 5) {
//Displays how many of each ticket were sold, and the total number of tickets sold
System.out.println("Motorcycle tickets sold: " + motoTicketCount);
System.out.println("Car tickets sold: " + carTicketCount);
System.out.println("Van tickets sold: " + vanTicketCount);
System.out.println("Truck tickets sold: " + truckTicketCount);
System.out.println("Total tickets sold: " + totalTicketCount);
}
if (userInput == 0) {
running = false; //terminates the program
}
}//end of else after the if (hasNextInt())
}//end of first if (hasNextInt())
}//end of try
catch (Exception e) //this SHOULD catch an invalid input error
{
System.out.println("Invalid input."); //displays invalid input in case the
userInput2 = keyb.next(); //discard the bad input
}
}
}
}
In here:
if (userInput >5 || userInput<0) //if one of these conditions are true, the user selected an option
{ //that is not mentioned
System.out.println("Invalid input."); //displays the Invalid input error
}
Change the System.out.println... to Throw new Exception("Invalid input.");
Note: this isn't really the correct use of an exception, but it may help you understand it.
in your catch block:
catch(Exception ex){
System.out.println(ex.toString());
}
EDIT: To try to understand the concept of the exception I would encourage you to try to change your input check to if(keyb.hasNext()) and then trying to cast the input to an integer with Integer.parseInt(keyb.next()); in your try block and catching the resultant NumberFormatException.
Also, rather than using the userInput2 variable to store the erroneous data you can just set userInput = -1; to restart the loop in your catch function.
Full code:
public class TollMachine
{
static boolean running = true; //variable to control whether the program should run
static int userInput = -1; //variable to store the user's input
static String userInput2 = ""; //variable to store the input in case user does not enter an integer
static int motoTicketCount = 0; //variable to store the number of tickets sold(moto)
static int carTicketCount = 0; //variable to store the number of tickets sold(car)
static int vanTicketCount = 0; //variable to store the number of tickets sold(van)
static int truckTicketCount = 0;//variable to store the number of tickets sold(truck)
static int totalTicketCount = 0;//variable to store the number of total tickets sold
static Scanner keyb = new Scanner(System.in); //variable to detect the user's input
public static void main(String[] args)
{
while (userInput != 0) //runs while userInput != 0
{
//This is the main menu, the user is prompted to choose an option
System.out.println("1. Motorcycle");
System.out.println("2. Car");
System.out.println("3. Van");
System.out.println("4. Truck");
System.out.println("5. Display total tickets sold.");
System.out.println("0. Exit");
try
{
/**
THIS THROWS YOUR EXCEPTION
**/
if (keyb.hasNext())
{
userInput = Interger.parseInt(keyb.next()); //stores the user's input to the userInput
if (userInput >5 || userInput<0) //if one of these conditions are true, the user selected an option
{ //that is not mentioned
System.out.println("Invalid input."); //displays the Invalid input error
}
else
{
//checks which option the user chose with multiple "if" conditions
if (userInput == 1)
{
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your motorcycle ticket.");
motoTicketCount++;
totalTicketCount++;
}
if (userInput == 2)
{
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your car ticket.");
carTicketCount++;
totalTicketCount++;
}
if (userInput == 3)
{
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your van ticket.");
vanTicketCount++;
totalTicketCount++;
}
if (userInput == 4)
{
//Displays an appropriate message to the user, and increases the two counters by 1
System.out.println("Here is your truck ticket.");
truckTicketCount++;
totalTicketCount++;
}
if (userInput == 5)
{
//Displays how many of each ticket were sold, and the total number of tickets sold
System.out.println("Motorcycle tickets sold: "+motoTicketCount);
System.out.println("Car tickets sold: "+carTicketCount);
System.out.println("Van tickets sold: "+vanTicketCount);
System.out.println("Truck tickets sold: "+truckTicketCount);
System.out.println("Total tickets sold: "+totalTicketCount);
}
if (userInput == 0)
{
running = false; //terminates the program
}
}//end of else after the if (hasNextInt())
}//end of first if (hasNextInt())
}//end of try
catch (NumberFormatException e) //this SHOULD catch an invalid input error
{
System.out.println("Invalid input."); //displays invalid input in case the
userInput = -1;
}
}
}
}
At work, so if what I gave you is super broken its because I can't compile and test right now. But this should give you the right idea.

checking input for positive number

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

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