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);
}
}
Related
I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}
Hi I needed help with doing a calculation in this right here. On the line where it has single, i want to add the number to the calculation but it just adds it as if im just writing the number itself in a sentence. How do i add it as if its a calculation, im very stuck and need help. (Its the last line of code). I also wanted to know how i can limit the amount of letters a user can input, since i only want them to either enter 's' or 'm'. How can i limit them to only these two so they dont use a letter like 'g' for example, since that wont work.
import java.util.Scanner;
public class FedTaxRate
{
public static void main(String[] args)
{
String maritalStatus;
double income;
int single = 32000;
int married = 64000;
Scanner status = new Scanner(System.in);
System.out.println ("Please enter your marital status: ");
maritalStatus = status.next();
Scanner amount = new Scanner(System.in);
System.out.print ("Please enter your income: ");
income = amount.nextDouble();
if (maritalStatus.equals("s") && income <= 32000 )
{
System.out.println ("The tax is " + income * 0.10 + ".");
}
else if (maritalStatus.equals("s") && income > 32000)
{
System.out.println ("The tax is " + (income - 32000) * 0.25 + single + ".");
}
}
}
To answer your second question about limiting the input, you can try using a switch case statement. The default allows you to write code for the case when maritalStatus is not equal to either "s" or "m". You can also create a do-while loop to keep asking for input until maritalStatus is equal to either "s" or "m".
Scanner status = new Scanner(System.in);
String maritalStatus = status.nextLine();
do {
System.out.println("Enter your marital status.")
switch (maritalStatus) {
case "s":
// your code here
break;
case "m":
// your code here
break;
default:
// here you specify what happens when maritalStatus is not "s" or "m"
System.out.println("Try again.");
break;
}
// loop while maritalStatus is not equal to "s" or "m"
} while (!("s".equalsIgnoreCase(maritalStatus)) &&
!("m".equalsIgnoreCase(maritalStatus)));
You only need one Scanner. You can use an else with your income test. I would suggest you calculate the tax once, and then display it with formatted IO. Something like,
public static void main(String[] args) {
int single = 32000;
int married = 64000;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your marital status: ");
String maritalStatus = sc.next();
System.out.print("Please enter your income: ");
double income = sc.nextDouble();
double tax;
if ("s".equalsIgnoreCase(maritalStatus)) {
if (income <= single) {
tax = income * 0.10;
} else {
tax = (income - single) * 0.25 + single;
}
} else {
if (income <= married) {
tax = income * 0.10;
} else {
tax = (income - married) * 0.25 + married;
}
}
System.out.printf("The tax is %.2f.%n", tax);
}
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);
import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank
{
double balance = 0;
double amount = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
//Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while
(!quit);
}
}
My code otherwise works fine but I can't seem to figure out why it won't stop repeatedly printing my error message for the user. If someone can point out my error for me that would be fantastic. I did have this same code in another question however they fixed my problem that I had in the last question and were unable to answer the problem that arose here.
You need to remove or comment out the following line from your code :
in.useDelimiter("\n");
This is causing the the character "\n" to be passed to the amount = in.nextDouble(), which in turn causes the InputMismatchException to be thrown , thus resulting in an infinite loop.
UPDATE : Working code and the Sample output for your convinience:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank {
public static void main(String[] args) {
double balance = 0;
double amount = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
System.out.print("User Input :");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println("Available Balance is : " + account1.getBalance());
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while (!quit);
}
}
}
Sample Output :
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :1
How Much would you like to deposit?
100
Depositing: 100.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :25
Error: Choice not recognized please choose again.
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :2
How Much would you like to withdraw?
25
Withdrawing: 25.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :3
Checking Balance.
Available Balance is : 75.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :0
Thanks for Using BankAccount Banking System!
Try this
String value = in.nextLine();
String v="";
for(int i=0;i<value.length();i++)
if(value.charAt(i)!='\n')
v+=value.charAt(i);
double amount =-1;
if(v!=null)
amount = Double.parseDouble(v);
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();
}
}