Java HashMap - get value from HashMap, user input - java

I am learning HashMap and trying to write a mortgage program. I thought that I would use the following in my HashMap
30 Years 3.95
15 Years 3.25
Here is so far what I have written
Loan Class: Getting user input
import java.util.*;
public class Loan {
private static HashMap<Integer,Double> rate = new HashMap<Integer,Double>();
public int getYear() {
rate.put(15, 3.25);
rate.put(30, 3.95);
System.out.println("Enter year: 15/30");
Scanner userInput = new Scanner(System.in);
int year = userInput.nextInt();
if (rate.containsKey(year)) {
}
return year;
}
}
HomeValue class: Showing home value
public class HomeValue {
public int hValue= 300000;
}
CaclPrice class: This is where calculation happens based on user input of the year
public class CalcPrice {
Loan ln= new Loan();
HomeValue hv= new HomeValue();
public double getPrice() {
if (ln.getYear()==15) {
System.out.println("House price is " + hv.hvalue *???
}
}
}
My Question: I do no want to hard code the calculation (home value* 3.25%) is there a way to get value from the HashMap based on the user input?
Thank You.

Map offers a get method which take the key as parameter.
So you can simply do rate.get(year).
Note that null will be returned if no value match the key.

Might I suggest restructuring the code a little bit. In your Loan class, I would recommend implementing a getRate() function instead of getYear() function.
Now, your Loan class might look something like this....
public class Loan {
private static HashMap<Integer,Double> rate = new HashMap<Integer,Double>();
Loan()
{
//I would recommend populating the rate HashMap
//in the constructor so it isn't populated
//every time you call getRate
rate.put(15, 3.25);
rate.put(30, 3.95);
}
public double getRate(int year) {
//Now you can just the desired rate
return rate.get(year);
}
}
And you can refactor your CalcPrice to look something like this....
public double getPrice(){
//I would recommend asking the user for input here
//Or even better, ask for it earlier in the program
//and pass it in as a parameter to this function
//You can easily get the rate now that you have the year
double rate = ln.getRate(year);
}
Now, you can just use the rate to complete your calculation.

Related

Why are the variables I'm requesting showing up as 0.0 when called from another class?

So basically my program is a StudySchedule where it takes user input (StudyTime, Subjects, PrioritizedSubjects, PriorityScale) and then creates a schedule based off each of those values. It begins with a class CreateSchedule which takes all the user input and then my other class CalculateScheduleTime takes the input and makes calculations (Calculate does extend to Create).
But when I request the variables from CreateSchedule, to CalculateScheduleTime, the variables appear as 0.0 rather than the number I had put in.
class CreateSchedule extends Test {
public String ScheduleName;
public double userStudyTime;
public double userSubjects;
public double userPrioritySubjects;
public double userSubjectScale;
public String getScheduleName() {
ScheduleName = setScheduleName();
return (ScheduleName);
}
public double getuserStudyTime() {
userStudyTime = setuserStudyTime();
return (userStudyTime);
}
public double getuserSubjects() {
userSubjects = setuserSubjects();
return (userSubjects);
}
public double getuserPrioritySubjects() {
userPrioritySubjects = setuserPrioritySubjects();
return (userPrioritySubjects);
}
public double getuserPriorityScale() {
userSubjectScale = setuserPriorityScale();
return (userSubjectScale);
}
public static String setScheduleName(){
System.out.println("What would you like to name your Schedule?");
Scanner sch = new Scanner(System.in);
return sch.nextLine();
}
public static double setuserStudyTime(){
System.out.println("How many hours are you studying for?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserSubjects (){
System.out.println("How many subjects are you studying?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserPrioritySubjects (){
System.out.println("How many subjects are you prioritizing?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserPriorityScale (){
System.out.println("On a scale of 1 - 5, how much priority would you like to give the prioritized subjects?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public double confirm() {
System.out.println("Input Results:");
System.out.println("Schedule Name: " + ScheduleName);
System.out.println("Study Time: " + userStudyTime);
System.out.println("Subjects: " + userSubjects);
System.out.println("Priority Subjects: " + userPrioritySubjects);
System.out.println("Priority Scale" + userSubjectScale);
return (0);
}
}
class CalculateScheduleTime extends CreateSchedule {
public double SubjectPriorityTime;
public double SubjectRemainderTime;
public CalculateScheduleTime() {
}
public double calcSubjectPriorityTime() {
System.out.println("Priority" + userSubjectScale);
double PriorityPercent = ((double) (userSubjectScale / 5.0));
System.out.println(userSubjectScale);
SubjectPriorityTime = ((double) (PriorityPercent * userStudyTime));
System.out.println("Time to Prioritized Subject is: " + SubjectPriorityTime);
return (SubjectPriorityTime);
}
public double calcSubjectRemainderTime() {
System.out.println("Remainder");
SubjectRemainderTime = ((double) (SubjectPriorityTime - userStudyTime));
System.out.println("Remainder time to Subject is: " + SubjectRemainderTime);
return (SubjectRemainderTime);
}
}
public class Test {
public static void main(String[] args) {
CreateSchedule user = new CreateSchedule();
user.getScheduleName();
user.getuserStudyTime();
user.getuserSubjects();
user.getuserPrioritySubjects();
user.getuserPriorityScale();
user.confirm();
CalculateScheduleTime calc = new CalculateScheduleTime();
calc.calcSubjectPriorityTime();
calc.calcSubjectRemainderTime();
}
}
That's not what subclassing is for.
A class describes what a given instance can do. "Dog" is a class. "Lassie" is an instance of it.
Subclassing is a thing you do to concepts, not instances. You might for example have a class "Animal", and a subclass "Dog": Dog simply specializes Animal: Any Dog is also an Animal and therefore can do and has all the properties that all Animals have, and perhaps a few additional things and properties (in java parlance: It would have all fields and methods of the superclass, and can add more. It cannot remove any).
When you write CreateSchedule user = new CreateSchedule(); that's like writing: Dog rover = new Dog(); - then you write CalculateScheduleTime calc = new CalculateScheduleTime(); which is like writing GermanSchnauser fifi = new GermanSchauser();.
You made a whole new dog, which gets its own copy of all those fields, which are all still 0 - uninitialized.
The 'calc' stuff should just go in CreateSchedule, probably. But there is a ton wrong with this code:
Classes represent tangible concepts. A good class name is 'Schedule'. Or perhaps 'ScheduleCreator'. 'CreateSchedule' is not a proper class name, and thinking about it as 'the code for creating schedules' is just plain incorrect, the right way to think about classes is about what they represent. "It is the code that explains what Schedules can do and how to create them", that's a proper way to think about it (and that class would be called Schedule. Not CreateSchedule).
methods named getX should not have sideeffects.
You should not be making a new scanner every time.
setters take an argument. They don't ask the user.
Separate concerns. A Schedule should just do schedule stuff - something else should be doing the interaction with the user. Either a main method or a class for this (perhaps TextBasedScheduleCreator).
Those calcX() methods store the result in a field, return it, and that field is never actually used anywhere. Just return it, don't have that field.

What is the function of the (.), or in other words, what does the period do? [duplicate]

This question already has answers here:
What is the purpose of Java DOT operator?
(3 answers)
Closed 3 years ago.
New to java programming. Can't seem to find what the period means when searching around...as in System.out.println() or when combining a Class with an instance variable, but CreditCard.balance may be an example. I came up with the following code partly by accident and partly by reason. Nonetheless, what is the (.)'s purpose.
public class CreditCard {
// data members
private static Person owner;
private static Money balance;
private static Money creditLimit;
public CreditCard(Person newCardHolder, Money creditLimit) {
CreditCard.owner = newCardHolder;
CreditCard.balance = new Money(0);
CreditCard.creditLimit = new Money(creditLimit);
}
public Money getBalance() {
Money balance = new Money(0.00);
return balance;
}
public Money getCreditLimit() {
Money creditLimit = new Money(1000.00);
return creditLimit;
}
public String getPersonals() {
return owner.toString();
}
public String getOwner() {
return owner.toString();
}
public void charge(Money amount) {
Money value = new Money(balance.add(amount));
value = balance;
if (value.compareTo(creditLimit) > 0) {
System.out.println("Exceeds credit limit");
} else {
balance = value;
System.out.println("Charge: " + amount);
}
}
public void payment(Money amount) {
Money value = new Money(balance.subtract(amount));
}
}
The output for the record here is
Diane Christie, 237J Harvey Hall, Menomonie, WI 54751
Balance: $0.00
Credit Limit: $1000.00
Attempting to charge $200.00
Charge: $200.00
Balance: $0.00
Attempting to charge $10.02
Charge: $10.02
Balance: $0.00
Attempting to pay $25.00
Balance: $0.00
Attempting to charge $990.00
Charge: $990.00
Balance: $0.00
if anyone wouldn't mind hinting at what I have done wrong in my execution, I'd appreciate that. My first question is the most crucial, however. Thank you to those who take the time to respond with their input.
Period indicates the namespace. It means that the method/variable after the period is belonging to the object before the period. It is not necessarily a function.
“Creditcard.balance” just tells compiler to access “balance” of neither global variable, nor any other object, but “Creditcard”.
As for your second question, I think it is a bit confusing.

How to set a variable as a class method and not as a static method

I'm trying to grasp some comments that were made to me by my professor on a programming assignment. The assignment was to write a program that calls upon another class. This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments. I received a 90% on my program for my grade.
The following comments were made about my assignment:
"Your setInterest method was to be a class method not an instance
method. Also, your call should have been
IWUnit4Ch13Investor.setInterest(rate);"
I'm not exactly following what I did wrong or how I can fix it. Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?
// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;
// main class
public class IWUnit4Ch13 {
public static void main(String[] args) {
// Declares local variables
double rate, INTEREST_RATE;
// Instantiate investor1 & investor2 objects using a two parameter constructor
IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
Scanner input = new Scanner(System.in);
// Receives the APR by the user
System.out.print("Please enter the APR in the form of .05 for 5%: ");
rate = input.nextDouble();
// Moves the decimal 2 places to the left (used later)
INTEREST_RATE = rate * 100;
// Sets the interest rate using a class variable
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
// Prints the header for the table
System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
System.out.println("Month Account # Balance Account # Balance");
System.out.println("----- --------- ------- --------- -------");
// Loop that prints each month on the table
// Uses class variables to add interest and get balance for display
for (int i = 1; i <= 15; i++) {
investor1.addInterest();
investor2.addInterest();
System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
}
// Prints the calculated interest earned by both investors
System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n");
System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n\n");
} // end of internal main
} // end of main class
// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {
// All variables are declared private
private static double interestRate; // class variable
private final int ACCOUNT_NUMBER; // declare constant ACCOUNT_NUMBER
private double balance; // instance variable called balance
private double initialBalance; // to hold the initial balance
private double interest; // to count how much interest was made
private double INTEREST_RATE; // used to convert the float interestRate to int
// Two parameter constructor to initialize account number and balance
public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
this.initialBalance = initialBalance;
this.ACCOUNT_NUMBER = acctNum;
balance = initialBalance;
}
// To return the balance to parent
public double getBalance() {
return balance;
}
// Class method to set the annual interest rate
public void setInterestRate(double rate) {
interestRate = rate;
}
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * interestRate/12.0;
}
// To get account number in parent
public int getACCOUNT_NUMBER() {
return ACCOUNT_NUMBER;
}
// Used to get the amount of interested earned during 15 months
public double getInterest() {
interest = balance - initialBalance;
return interest;
}
} // end of class
Thank you all in advance for your help.
Terms
First of, please don't confuse terms. A variable is different to a method:
// A class
public class Dog {
// Member variable
private String name;
// Method
public void bark() {
// Variable
String textToBark = "Wuff";
// Call to a method
System.out.println(textToBark);
}
}
Elsewhere:
// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");
Explanation
Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods
Solution
So the method should look like this:
// Method to set the annual interest rate
public static void setInterestRate(double rate) {
IWUnit4Ch13Investor.interestRate = rate;
}
Where interestRate then also needs to be declared static (which you already did):
// To count how much interest was made
private static double interestRate;
To indicate the access of static variables one should add the class name before, so instead write it like this:
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}
The same holds for calling static methods, instead of
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
do this
IWUnit4Ch13Investor.setInterestRate(rate);
Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.
So a static variable is shared by all instances of the class.
If you want all investors to be forced to share the same interest rate, use a static variable.
Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:
public static void setInterestRate(double rate) {
interestRate = rate;
}
private static double interestRate;
You would then call the static method by specifying the class name, not the instance variable. Note that you can call the static method before you even have any instances of the class, and you only need to call it once:
Investor.setInterestRate(0.05);
Investor i1 = new Investor();
Investor i2 = new Investor();
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
If you want each investor to be able to have different interest rates, do not use a static variable, use a member variable and method:
public void setInterestRate(double rate) {
interestRate = rate;
}
private double interestRate;
You then call the method by specifying the instance variable:
Investor i1 = new Investor();
Investor i2 = new Investor();
i1.setInterestRate(0.04);
i2.setInterestRate(0.06);
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
Also, none of that really matters because the output is wrong:
double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;
The system shall not fail

Calling a method, but won't return the values. Java

So I have an assignment where I have to make a bank account. Long story short I have a class that has your actions (deposit, withdraw etc) in methods, and a Driver which would fills in the blanks (i.e client name, balance etc.) as well it calls the methods from the other class.
Now my issue. For an example, when I deposit, my variables send fine to the method and do the math correctly and have the correct balance, but returning the balance's new value is an issue. It is still the same value it was before in the driver.
This is my driver's deposit code
String deposit1 = JOptionPane.showInputDialog ("How much would you like to deposit?");
int deposit = Integer.parseInt (deposit1);
myBank.getDeposit(deposit, balance);
This is my deposit method code
public void getDeposit(int deposit, int balance)
{
if (deposit<0)
{
System.out.println ("Invalid Number");
deposit=0;
}
balance =balance + deposit;
}
Any help would be greatly appreciated, can't seem to find any solutions and I've been stuck for some time
Thanks
P.S This is my first time on these forums so sorry if I did anything wrong
P.P.S My java knowledge isn't that high, still just a beginner
Edit:
We have learned instance variables as well as touched a little upon return statements, we haven't learned anything about passby. By return I mean giving the driver the correct value, sorry if that threw you off
Edit2: Thank youuu so much user1710742, finally got it. I understand now. Makes sense
The problem is you are attempting to change a copy of the variable, not the exact one that you gave to the method. When you exit the method, the copy is destroyed, and you are left with just the unchanged original value.
The method can't return a value unless you tell it to with a return statement.
public int getDeposit(int deposit, int balance)
{
if (deposit<0)
{
System.out.println ("Invalid Number");
deposit=0;
}
return balance + deposit;
}
call with:
int total = myBank.getDeposit(deposit, balance);
You can add a new variable call dep with int data type :
int dep = myBank.getDeposit(deposit, balance);
after that change your method type from void to int and add return statement of variable that you want :
public int getDeposit(int deposit, int balance)
{
if (deposit<0)
{
System.out.println ("Invalid Number");
deposit=0;
}
balance =balance + deposit;
return balance;
}
start with the basics of the language. Yet, Keep in mind that understanding the problem is the only true way to reach the right solution. Don't let the language get in the way of the logic. You'll get the syntax down fast enough. You've got a good start. It's easy to get drawn into just finding A solution, instead of finding THE solution. The method of solving the problem is more important than having an answer. Try the link below for the basics on the return value.
http://www.homeandlearn.co.uk/java/java_methods.html
You should not name your method getDeposit() since the return type is void. Instead, just name it deposit(), because you actually do an action.
Use a private instance variable named balance, in your Bank class.
Use a getter for your balance field.
This snippet should work:
public class BankAccount {
private int balance;
public static void main(String[] args) {
BankAccount account = new BankAccount();
String deposit = JOptionPane.showInputDialog ("How much would you like to deposit?");
account.deposit(Integer.parseInt (deposit));
deposit = JOptionPane.showInputDialog ("How much would you like to deposit?");
account.deposit(Integer.parseInt (deposit));
System.out.println(account.getBalance());
}
public void deposit(int deposit){
if (deposit < 0){
System.out.println ("Invalid Number");
}else{
balance += deposit;
}
}
public int getBalance(){
return balance;
}
}
I am not totaly sure if you are actually doing what you want to do..
To me, it seems like you want to create a class called Bank and have a private variable there, called ballance. then methods for manipulating that value..
public static class Bank{
private int balance = 0;
// this method won't return any value. it will only change
// the banks internal state, therefor we write "void"!
public void deposit(int deposit){
if(deposit<0){
// using System.err instead of System.out will be handled differently
// by java. It is meant to be used for error messages. some consoles make
// these texts pop out more (like displyaing it in read)
System.err.println ("Invalid Number");
}else{
// balance += deposit is a short way of writing balance = balance + deposit;
balance += deposit;
}
}
// this method will return an int value to who ever called it.
// you can tell, because it says int after public
public int getBalance(){
return balance;
}
}
And then a main method which handles the bank:
Bank bank = new Bank();
bank.deposit(5);
bank.deposit(8);
int balance = bank.getBalance(); // will be 13
System.out.println("balance is "+balance);
More on System.err can be found in the oracle docs about System
Hope I could help

Java-OOP I keep on getting this strange output

I am currently taking Computer Science at school and I am a bit stuck on my lab.
The directions are listed below and we are required to use an OOP.
The problem is that my output that I get is super strange and I really don't know what is going on.
The output that I get after running the file DiscountRunner.java (code listed below) is:
Enter the original bill amount :: 4000
Discount#1d1be4e
Why do I keep on getting the Discount#1d1be4e part?
/**==================================================================================================
* Objective : This lab was designed to teach you how to use if statements.
* Lab Description : Determine the amount of discount a person should receive.
* If the bill is more than 2000, then the person should receive a 15% discount.
* If the bill is 2000 dollars or less, the person does not receive a
* discount of any kind.
===================================================================================================*/
import static java.lang.System.*;
import java.util.Scanner;
public class DiscountRunner
{
public static void main( String [] args )
{
Scanner keyboard = new Scanner(System.in);
out.print("Enter the original bill amount :: ");
int amt = keyboard.nextInt();
int Discount;
Discount bill=new Discount();
bill.getDiscountedBill();
System.out.println(bill);
//instantiate a new Discount object called "bill"
//print the output of bill.getDiscountedBill() with amt as the parameter
}
}
That is file one.
Here is file two.
import static java.lang.System.*;
import java.util.Scanner;
public class Discount
{
//instance variables and constructors could be used, but are not really needed
int amt;
int bill;
//getDiscountedBill() will return final amount of the bill
// if the bill is >2000, the bill receives a 15% discount
public int getDiscountedBill()
{
if ( amt>2000)
bill=amt*(int).85;
if ( amt<=2000)
bill=amt*1;
return bill;
}
}
System.out.println() method will try to convert a object to a string before printing it out. In order to do this it will normally call Object.toString() method. The default implementation of said method is to generate a string containing the object type concatenated with the in-memory address of the object. This is what is happening to you.
To fix it you need to provide a toString() implementation to the Discount method.
You get this because of this line:
System.out.println(bill);
You are printing the object which calls the default toString() implementation of Discount (inherited from Object). You can overwrite toString() in Discount to get a custom representation but I guess you just want to remove this System.out statement there.
You had some little mistakes of Type conversions and some in receiving value from method.
Find below the working code
import static java.lang.System.*;
import java.util.Scanner;
public class DiscountRunner
{
public static void main( String [] args )
{
Scanner keyboard = new Scanner(System.in);
Discount bill=new Discount();
out.print("Enter the original bill amount :: ");
bill.amt = keyboard.nextInt();
int discount;
discount=bill.getDiscountedBill();
System.out.println(discount);
//instantiate a new Discount object called "bill"
//print the output of bill.getDiscountedBill() with amt as the parameter
}
}
import static java.lang.System.*;
import java.util.Scanner;
public class Discount
{
//instance variables and constructors could be used, but are not really needed
int amt;
int bill;
//getDiscountedBill() will return final amount of the bill
// if the bill is >2000, the bill receives a 15% discount
public int getDiscountedBill()
{
if ( amt>2000)
**bill=(int)(amt*.85);**
if ( amt<=2000)
bill=amt*1;
return bill;
}
}
Let me know if you are not getting something.
Accept the answer if it solves your Problem.
You didn't override the toString() method in the Discount class which is inherited by the Java class Object. This causes the output you listed.
Whenever you pass a Object to System.out.println it executes its toString method, Default implementation of toString prints ClassName with its hashCode. you can override toString method. add below code snnipet to your Discount Class and it will run as per your expectation
#Override
public String toString()
{
return "Bill Amount After Discount is " + bill ;
}

Categories