EDIT:
you guys are really fast at answering. I love it.
I can not believe I missed the fact that I tried instantiating the NumberFormat class meanwhile when I previously used it, I didn't do that. I stared at this code for so long too. Looks like I have a lot to learn when it comes to paying close attention to detail.
Thanks, everyone.
I'm using the NumberFormat class (or method, I'm still getting used to the terminology), but when I compile the program I get a "cannot find symbol" pointing at the decimal in "NumberFormat.getPercentInstance();" but I don't underhand why. Here's the code:
import java.util.Scanner;
import java.text.NumberFormat;
public class StudentAverages
{
//----------------------------------------------------------------
// Reads a grade from the user and prints averages accordingly.
//----------------------------------------------------------------
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
NumberFormat fmt = new NumberFormat.getPercentInstance();
System.out.print("Enter the name of the first student: ");
String name1 = scan.nextLine();
int lab1, lab2, lab3, min = 0;
System.out.print("Enter the lab assignment grades of "+name1+": ");
lab1 = scan.nextInt();
lab2 = scan.nextInt();
lab3 = scan.nextInt();
System.out.print("Enter the project grades of "+name1+": ");
int proj1 = scan.nextInt();
int proj2 = scan.nextInt();
System.out.print("Enter the midterm grade of "+name1+ ": ");
double mid1 = scan.nextDouble();
System.out.print("Enter the final grade of "+name1+": ");
double fin1 = scan.nextDouble(); // fin used so as to not confuse with CONSTANT final
double avgLab1 = (lab1 + lab2 + lab3) / 3;
double avgProj1 = (proj1 + proj2) / 2;
double grade1 = (25 * avgLab1 + 40 * avgProj1 + 15 * mid1 + 20 * fin1) / 10000;
System.out.println();
System.out.println("Student's name " + name1);
System.out.println("Lab average for "+name1+": " + avgLab1);
System.out.println("Project average for "+name1+": " + avgProj1);
System.out.println("Total grade for "+name1+": " + fmt.format(grade1));
New at coding. Thanks for any help. I cross referenced the syntax from the book I'm using, and it checks out. I even checked previous code, and I did nothing differently, or at least nothing that I can see. So why would the compiler say it cannot find the symbol?
Instead of:
NumberFormat fmt = new NumberFormat.getPercentInstance();
it should be:
NumberFormat fmt = NumberFormat.getPercentInstance();
because, you want to call the static method getPercentInstance from class NumberFormat.
Furthermore (as Pshemo said), the NumberFormat class is abstract, so you cannot instantiate it with the new keyword.
Remove the new from:
NumberFormat fmt = new NumberFormat.getPercentInstance();
You are calling a static method.
Remove new keyword in line
NumberFormat fmt = new NumberFormat.getPercentInstance();
NumberFormat is abstract class which means you can't create instance of it.
You need instance of class which extends it, and such instance you can get for instance via getPercentInstance method.
Related
All I want it to do is read input typed by the user as double type, and then convert it to another number. I'm also aware the equation isn't complete, not worried about that right now, just want it to run. I don't understand what I have done wrong.
public class EuroShoe {
public static void main(String[] args) {
double
footLength,
euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
footLength = Keyboard.readDouble(); // line 25
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
If you are following a tutorial, please check on the imports that were mentioned. But to answer your question and make your program work here's an answer.
import java.util.Scanner
public class EuroShoe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i =
double footLength, euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
// The statement below calls the "scanner" object to get the user input of value "double"
footLength = scanner.nextDouble();
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
Make sure to put this statement above
import java.util.Scanner // imports the specific Scanner class under the 'util' namespace
or you can use this as well
import java.util.* // imports every class under the 'util' namespace
Hope this helps you with your problem and keep coding! :)
This worked:
package euroshoe;
import java.util.Scanner;
public class EuroShoe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
double footLength = input.nextDouble();
double euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
I am trying to program an amortization calculator in which the user can enter a value for balance, a value for their interest rate in decimal form, and a value for monthly payment. With this information I want to output an interest amount in dollars, a principal amount, and a new balance. Here is my code:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner pmt, interest, balance = new Scanner(System.in);
System.out.println("What is your balance?");
double b = balance.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = interest.nextDouble();
System.out.println("What is your monthly payment?");
double p = pmt.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
You should not declare 3 scanners to read from the standard input. Declare one and just keep reading from it. Like this:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("What is your balance?");
double b = input.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = input.nextDouble();
System.out.println("What is your monthly payment?");
double p = input.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
The main point here is that a scanner is the object that reads from an input stream, not the value being read. You don't need a new scanner for every value you want to read.
As #nhouser9 says, you don't need three scanners and answering your question the compiler says that the variables are not initialized because you are only initializing the last of them (balance). Multiple initializing in java won't functions as you expected (initialize all the variables with the same value).
Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.
I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}
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 :-)