Code:
import java.util.Scanner;
public class sdusti00lab1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double AA = 8.25;
double CA = 6.50;
double ACP = 9.00;
double CPC = 6.25;
int numA, numC;
double numSP, numLP;
Scanner keys = new Scanner(System.in);
System.out.print(" enter number of adults ");
numA = keys.nextInt();
System.out.println(" enter number of children ");
numC = keys.nextInt();
System.out.println(" enter number of small popcorn");
numSP = keys.nextDouble();
System.out.println(" enter number of large popcorn");
numLP = keys.nextDouble();
double AAddPrice = (numA*AA);
double CAddPrice = (numC*CA);
double ACPT = ((ACP*.094)*AA);
double CPCT = ((CPC*.094)*CA);
double SPTax = (ACP*.094);
double LPTax = (CPC*.094);
System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
System.out.println("Child admission "+"\t"+numC + "\t$" + CAddPrice);
System.out.println("Adult popcorn "+"\t\t"+ACP + "\t$" + ACPT);
System.out.println("Child popcorn "+"\t\t"+CPC + "\t$" + CPCT);
System.out.println("Tax "+"\t\t\t$"+ (SPTax + LPTax));
System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) );
}
}
I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.
Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.
System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);
There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.
The important aspect to understand here: that process works by you
A) specifying a format that describes how your output should look like
B) you calling a formatter with that format and the numbers to format
Related
This question already has answers here:
What data type to use for money in Java? [closed]
(11 answers)
Closed 3 years ago.
For a homework problem, I was tasked to make an application in java (using Eclipse) to calculate the worth of euro's to Dollars, Pounds and Lira. Pounds and Lira work fine, but for whatever reason when converting euro's Dollars, it leads to a lot of numbers behind the decimal point on certain numbers (Such as 50)
The code is in dutch in several places but the general outline should be clear.
I've talked about this with my teacher, but even he couldn't help me with my answer.
import java.util.Scanner;
public class Tests
{
public static void main(String[] args)
{
int keuze;
double bedrag;
double factord=1.1;
double factorp=0.87;
double factorl=5.38;
Scanner c = new Scanner(System.in);
System.out.print("Kies uw valuta: \n 1 - Amerikaanse
Dollar\n 2 - Engelse Pond\n 3 - Turkse Lira\n");
keuze = c.nextInt();
if(keuze == 1)
{
System.out.print("Voer het gewenste bedrag in euro's: ");
bedrag = c.nextDouble();
System.out.println( bedrag * factord + " Dollar");
}
My expected result when entering a number (For example) 20, is 22 (Because the factor is 1.1). This causes no problem, but (for example) entering 50, it leads to 55.00000000000001.
You should use BigDecimal:
public static void main(String[] args) {
int keuze = 1;
BigDecimal bedrag;
BigDecimal factord = BigDecimal.valueOf(1.1);
BigDecimal factorp = BigDecimal.valueOf(0.87);
BigDecimal factorl = BigDecimal.valueOf(5.38);
Scanner c = new Scanner(System.in);
System.out.print("Kies uw valuta: \n 1 - AmerikaanseDollar\n 2 - Engelse Pond\n 3 - Turkse Lira\n");
if(keuze == 1) {
keuze = c.nextInt();
System.out.print("Voer het gewenste bedrag in euro's: ");
bedrag = BigDecimal.valueOf(c.nextDouble());
System.out.println(bedrag.multiply(factord) + " Dollar");
}
}
Output:
Voer het gewenste bedrag in euro's: 50
55.00 Dollar
Have a look at : Double vs. BigDecimal
It's depend on how many place you want to display in your output. You have to format these according to your need. Below code use DecimalFormat to perform these action.
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static DecimalFormat df2 = new DecimalFormat("#.##");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df2.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df2.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble : " + df2.format(input)); //3.14
df2.setRoundingMode(RoundingMode.UP);
System.out.println("double : " + df2.format(input)); //3.15
}
Output
double : 3.14159265359
double : 3.14
double : 3.14
double : 3.15
I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
}
getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)
Here are my two java files that I am working with. The problem I am having is getting the getPosNum method (highlighted below) to take the number the user inputs and see if that number is positive rather than doing what is doing right now, which is:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Please enter a positive number: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
Rather than getting it to say something like this:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Enter the first principal amount: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
How can I fix this problem and make it read correctly? Am I making sense?
public class Finance
{
public static double getPosNum (String prompt)
{
double num;
num = Input.readDouble("Please enter a positive number: ");
while (num <= 0.0)
num = Input.readDouble("ERROR: " + num +
" is not positive; try again: ");
Output.showValue("You entered ", num);
return num;
} // method getPosNum
public static void outFinances (double prin, double rate, double years, double fv)
{
Output.showMessage("The original amount invested was $" + prin + ",\nand the annual interest rate was set at " + rate + "%.\nIt has been " + years + " years since the investment was made,\nand the future value of the investment after that many years is $" + fv + ".");
} // method outFinances
public static double futureValue (double prin, double rate, double years)
{
double FV, P, r, n;
P = prin;
r = rate;
n = years;
FV = P * Math.pow((1 + (r / 100)),(n));
return FV;
} // method outFinances
} // class Finance
// File: Prog12.java
// CS200 Lab 12 Main
// Author: Ryan Pech
// Created: February 19, 2011
public class Prog12
{
public static void main (String [] args)
{
double p, r, y, fv;
Output.showMessage("First Investment");
p = Finance.getPosNum("Enter the first principal amount: ");
r = Finance.getPosNum("Enter the first interest rate: ");
y = Finance.getPosNum("Enter the first number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
Output.showMessage("Second Investment");
p = Finance.getPosNum("Enter the second principal amount: ");
r = Finance.getPosNum("Enter the second interest rate: ");
y = Finance.getPosNum("Enter the second number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
} // method main
} // class Prog12
// File: Finance.java
// CS200 Lab 12
// Author: Ryan Pech
// Created: February 19, 2011
Your getPostNum() accepts a parameter called prompt, but you never use that variable in that method at all. Instead of hardcoding Please enter a positive number:, substitute that string with that prompt variable, like this:-
Change...
num = Input.readDouble("Please enter a positive number: ");
... to...
num = Input.readDouble(prompt);
It should be obvious that it's printing "Please enter a positive number: " because you explicitly told it to in the getPosNum() method.
Using
num = Input.readDouble(prompt)
will solve your problem. A better way to go about this is to restrict printing to your main() method and use getPosNum() for input only. This way you know explicitly what you are printing every time. Something like
System.out.println("Enter the first principle amount.");
num = Input.readDouble();
and then perform some negative number checks.