Using method to call for a y/n answer - java

I have this code. The askToContinue() method is being called to ask the user if they would like to continue but my problem is it just ignores the choice and starts the program again no matter what I enter. What am I missing in the code that is causing it to ignore my choice?
public class FutureValueApp {
public static void main(String[] args) {
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment,
interestRate, years, futureValue);
System.out.println();
askToContinue(sc);
}
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue){
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
System.out.println(results);
}
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next();
System.out.println();
return choice;
}

You're on the right track. Change this
askToContinue(sc);
to
choice = askToContinue(sc);
Because you need to assign the value returned from askToContinue to the local reference named choice.

You are not assigning the result of askToContinue to the choice variable which is checked in the loop.
Possibly the confusion is the choice variable inside the askToContinue method. Note, this is a different variable and does not affect the choice variable checked in the while statement.

When you define a variable inside a method, it is not recognized by the code outside of your method, even if it has the same name. So, in your code for example, you have,
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next(); // this choice variable exists only for the
// askToContinue method
// Once you assign it over here and return it
// with the code below, you should use the returned
// value to update the variable choice, which is
// defined outside your askToContinue method
System.out.println();
return choice;
}
So, as the other answers have pointed out, if you do,
choice = askToContinue(sc);
then the code will run fine since the choice variable defined in the main method will get updated according to the value you input

Based on
John Camerin's answer,to skip double assigning in your code, you can make your choice variable as global static variable by define it in your class :
public class FutureValueApp {
public static String choice;
}
Or send it as second parameter in your method :
askToContinue(sc,choice);

Related

Program repeats user input even when an equivalency condition / the first if-statement has been met

I need an instance in my program to work in that if the user inputs a payment number (payment) that is equal to the total price of a checkout with taxation (price3), the program will just list 0.00 as change and not repeat user input as if the user's payment is less than the price. However, when payment equals price3 (payment - price3 == 0), the program goes to the else-if statement. How do I fix this?
Example: price3 == 28, payment == 28, the output after payment input is "You still owe..." and so on instead of "Your change is $0.00".
I think it is skipping the first if-statement in the while loop, but I have no idea why. I already tried moving around the if-statements in the while-loop to no avail.
There are no error messages.
Note: I am still trying to learn Java. Just started recently.
The program code which my question references is displayed below:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
The core of your problem lies in (1) expecting exact equality of floating-point value, and (2) displaying quantities to 2 decimal places.
Given the user is told the amount to pay (price3) using 2 places of decimals, even if he enters that exact same value as payment, it may not match the true value of price3.
Ideally you should do all calculation in pennies (or whatever the smaller unit of this currency is). Failing that, your criterion for having paid the right amount should be something like the difference between price and payment is less than 0.01.
In the stated case
Example: price3 == 28, payment == 28, the output after payment input
is "You still owe..." and so on instead of "Your change is $0.00".
if the price before tax is 26.415 it makes the price after tax 27.9999, which displays as 28.00 but is not equal to 28.00. Neither 26.41 nor 26.42 get you to an after-tax displayed price of 28.00.
that is happening because of price3=price2+(price2*0.06). So, when it is comparing payment with price3, it is always less. See below

Void methods cannot return a value -Java

I am sure this is a dumb question but i have been at it for quite a bit.. I am trying to create a java program that calculates compound interest based off a user input of years and amount of money. But i keep getting an error that a void method cannot return a value. So i switch the method to a double because thats what will be returned, but than it tells me that a double method must return a double. Even tho im returning a double in the loop... Please help
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}
change your for to this
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);
Make the method a double and change
double MoneySaved = reader.nextInt();
to
double MoneySaved = reader.nextDouble();
Also I do not see your declaration of 'Total'; make sure that is declared as a double.
First, main Java method must be void and void methods cannot return a value(even compiler tells you that), although you can use a return statement to break execution of the method and return to calling method.
So answering your question, you have to create method that returns double and then just prints it in your main method or do not return anything and just replace
return Total;
with
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS: it looks like you are new to Java, so for a start read some content about Java, for example offical oracle tutorial

Java User input Validation

I am trying to figure out how to validate the input of a user. I want the user to enter a double but if the user enters a string I want the question repeated until a double is entered. Iv'e searched but I couldn't find anything. Below is my code so far any help is appreciated. I have to use a do while loop I am stuck on what to put in the while loop to make sure the input is a double and not a string.
public class FarenheitToCelsius {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double fahrenheit, celsius;
Scanner in = new Scanner(System.in);
do{
System.out.printf("Enter a fahrenheit degree: ");
fahrenheit = in.nextDouble();
}
while();
celsius = ((fahrenheit - 32)*5)/9;
System.out.println("Celsius value of Fahrenheit value " + fahrenheit + " is " + celsius);
One trick you can use here is to read the entire user input as a string, which would allow any type of input (string, double, or anything else). Then, use Double#parseDouble() to try to convert that input to a bona-fide double value. Should an exception occur, allow the loop to continue, otherwise, end the loop and continue with the rest of your program.
Scanner in = new Scanner(System.in);
boolean isValid;
do {
System.out.printf("Enter a fahrenheit degree: ");
isValid = false;
String input = in.nextLine();
try {
fahrenheit = Double.parseDouble(input);
isValid = true;
}
catch (Exception e) {
// do something
}
} while(!isValid);
celsius = ((fahrenheit - 32) * 5) / 9;

Local variable can't take methods parameters

I am new To Java please help me, my local variable can't take me methods parameters.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.DecimalFormat; //I can not get my local variables in my
// main to accept my methods parameters.
// This is my program.
public class AccountBank
{
public static void main (String[] args) throws IOException
{
// Calling in my Class
Accountclass BankAcc = new Accountclass();
// initialize both there variables in. order to use them in a for loop.
double depDrw = 0;// this are one of the variables that is giving me problems
double withDrw = 0; // this is the other that is giving me problems
double totalW = 0;
double totalD = 0;
// declaring all my variables
String name="";
double month;
double startBal;
// This section will greet and accept input by asking the user to enter the starting alance and set it in my class
// Greetings
JOptionPane.showMessageDialog(null,"Lets Get Started");
// receiving input for my name variable
name = JOptionPane.showInputDialog(null, "Please Enter Your Name Below: ");
// ask user for starting balance
startBal = Double.parseDouble(JOptionPane.showInputDialog("What Is The Starting Balance In Your Account:"));
// This will set the value in my class
BankAcc.setBal(startBal);
// ask user how many months has the account been active
month = Double.parseDouble(JOptionPane.showInputDialog("Months That Account Has Been Active:"));
// This section will accept input by asking the user to enter each amount deposited every month from the account set it in my class.
// This will be shown in the message box
depDrw = depositTotal(deposit); << // I am having trouble here it wont take my parameters variable which I created on the buttom. please help
// This will sum up every amount the user enters in the message box.
totalD += depDrw;
// This will set the value in my class
BankAcc.setdeposit(totalD);
// This section will accept input by asking the user to enter each amount withdrawn every month from the account and set it in my class
// This will be shown in the message box
withDrw = withdrawTotal(wit); // <<< I am having problem here this variable does not take the value of my methods parameter, which i created on the bottom of this page.
// This will sum up every amount the user enters in the message box.
totalW += withDrw;
// This will set the value in my class
BankAcc.setwithdraws(totalW);
//This section will display the " monthly interest rate, monthly interest earned, total amount deposited, total amount withdrawn, and the final balance of the account."
DecimalFormat formatter = new DecimalFormat("#0.0000");
DecimalFormat formatter2 = new DecimalFormat("#0.0");
DecimalFormat formatter3 = new DecimalFormat("#0.00");
//Get the calculations from the savings account class and display them.
JOptionPane.showMessageDialog(null," Account Name: " +name+"\n \n Your Monthly Interest Rate Is ..... "
+ formatter.format(BankAcc.monthInt())+"%" + "\n \n Your Monthly Interest Earned Was ..... $"
+ formatter2.format(BankAcc.GetInt()) + "\n \n Your Overall Amount With Deposited Was ..... $" + totalD +
" \n \n Your Overall Amount WithDrawn Was ..... $" + totalW + " \n \n Your Remaining Balance Is ..... $"
+ formatter3.format(BankAcc.getFinalbal()),"Results", JOptionPane.PLAIN_MESSAGE );
}
public static double depositTotal( String deposit)
throws IOException
{
double sales;
double totalDeposit = 0;
File file = new File ("deposits.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
inputfile.close();
return totalDeposit;
}
public static double withdrawTotal( String wit)
throws IOException
{
double sales;
double totalwithdraws = 0;
File file = new File ("withdraws.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalwithdraws += sales;
}
inputfile.close();
return totalwithdraws;
}
Your while loop is
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
There shouldn't be a ; after the while (inputfile.hasNextDouble())
while (inputfile.hasNextDouble())
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
Similarly for other while loops, remove the ;
Change your method declaration so it doesn't receive any parameter. And because it's returning a double, you may store the value it returns in a double variable:
double deposit = depositTotal();
In your depositTotal() method:
public static double depositTotal() throws IOException {
...
}

Getting NaN when using get method

I'm making an BMI calculator for a diet programming I'm making for a piece of coursework. Originally I was making a a couple variables public static to get variables from another class. My BMI calculator worked fine this way.
I then figured out that I could use a get method (for more marks). So I changed by the previous variables to private and used a get method. But when I run this program I get NaN when the program prints out the the variable that holds the BMI, this never happened before!
Can anyone help?
import java.util.Scanner;
public class Weight {
private Scanner input;
private String readInput;
private String userWeightIsPounds;
private String userWeightIsStones;
private Scanner input2;
public static double userWeight;
public Weight(){
userWeightIsPounds = ("Pounds");
userWeightIsStones = ("Stones");
}
public void findOutUserWeightMessage(){
System.out.println("Firstly Do you weigh yourself in pounds or stones?");
}
public void findOutUserWeight(){
input = new Scanner (System.in);
readInput = input.nextLine();
if(readInput.equals(userWeightIsPounds)){
System.out.println("Ok then, enter your weight in pounds please.");
}
if(readInput.equals(userWeightIsStones)){
System.out.println("Ok enter your weight in stones please.");
}
input2 = new Scanner (System.in);
userWeight = input2.nextFloat();
if (userWeight > 20){
System.out.println("You've enetered your weight as " + userWeight + " lbs. I'll save that information for later.");
}else{
userWeight = userWeight * 14;
System.out.println("I've converted your weight into pounds for you. You weigh " + userWeight + " lbs. I'll save that information for later.");
}
}
public double static getUserWeight(){
return userWeight;
}
}
And there is come code the the class that does the calculations. Ignore some of the println's I was trying to find out what was happening with my variables.
public class BMI {
private double userHeightSqaured;
private double bmiMutiplier;
private double weightDivideHeight;
private double userBmi;
private double userWeightBmi;
private double userHeightBmi;
BMI(){
bmiMutiplier = 703;
userWeightBmi = Weight.getUserWeight();
userHeightBmi = Height.getUserHeight();
}
public void startUpBmiMessage(){
System.out.print("Lets start with your BMI then shall we? ");
}
public void calculateUserBmi(){
System.out.println("userWeightBmi is " + userWeightBmi);
System.out.println("userWeightBmi is " + userHeightSqaured);
userHeightSqaured = userHeightBmi * userHeightBmi;
System.out.println("userHeightSqaured is " + userHeightSqaured);
weightDivideHeight = userWeightBmi/userHeightSqaured;
System.out.println("weightDivideHeight is " + weightDivideHeight);
userBmi = weightDivideHeight * bmiMutiplier;
System.out.println("weightDivideHeight is " + weightDivideHeight);
System.out.println("bmiMutiplier is " + bmiMutiplier);
}
public void calculateUserBmiMessage(){
System.out.println("Your bmi is " + userBmi);
}
}
It sounds like you're trying to write a Java program that performs some calculations, and the result of your calculation is NaN - you can refer to the question In Java, what does NaN mean? for some info on NaN.
As for resolving your problem without seeing any code, and assuming your calculation worked fine with the same input before, it sounds like your switch from public static variables to private ones with getters has probably left some of your variables uninitialized, so their value defaults to 0 - Division by 0 is a common cause of NaN.
The reason for the NaN is that this statement:
weightDivideHeight = userWeightBmi/userHeightSqaured;
divided zero by zero. In other words userWeightBmi and userHeightSqaured were both zero at that point.
The root problem seems to be that you haven't got your head around the difference between static and instance variables. And when you should / should not use the two kinds of variable.

Categories