Passing Value In Java - java

I was given a task to create a java program that use this 3 classes. Main class, Menu class and Coffee Class. Now i need to pass value from menu class to coffee class. But the problem is i dont exactly know how to do it since im still new with java.
CoffType pass the value to CoffeeName.
NumBag pass the value to NumberOfBag.
This is menu class(programmer defined class 1)
import java.util.*;
public class Menu {
Scanner scan = new Scanner(System.in);
public String coffType;
public int numBag;
public void setCoffType() {
System.out.println("\t\tChoose Your Coffee");
System.out.println("\n[1] Arabica\tRM12.50 per bag");
System.out.println("\n[2] Robusta\tRM15.00 per bag");
coffType = scan.nextLine();
}
public void setNumBag() {
System.out.println("Enter amount you wish to buy");
numBag = scan.nextInt();
}
}
Coffee Class(programmer defined class 2)
public class Coffee{
private String coffeeName;
private double coffeePrice;
private double amountPay;
private int numberOfBag;
private double discount;
public Coffee() { // constructor
coffeeName = "unknown";
coffeePrice = 0.00;
amountPay = 0.00;
numberOfBag = 0;
discount = 0.00;
}
public double getCoffeePrice() {
if(coffeeName.equalsIgnoreCase("arabica")) {
coffeePrice = 12.50 * numberOfBag;
}
else if(coffeeName.equalsIgnoreCase("robusta")) {
coffeePrice = 15.00 * numberOfBag;
}
System.out.println("Price RM: " +coffeePrice);
return coffeePrice;
}
public double getDiscount() {
if(numberOfBag>0 && numberOfBag<=50) {
discount = coffeePrice*0;
}
if(numberOfBag>50 && numberOfBag<=100) {
discount = coffeePrice*0.10;
}
if(numberOfBag>100 && numberOfBag<=150) {
discount = coffeePrice*0.15;
}
if(numberOfBag>150 && numberOfBag<=200) {
discount = coffeePrice*0.20;
}
if(numberOfBag>200) {
discount = coffeePrice*0.25;
}
System.out.println("Discount RM: " +discount);
return discount;
}
public double getAmountPay() {
amountPay = coffeePrice - discount;
System.out.println("\nTotal Need To Pay RM: " +amountPay);
return amountPay;
}
}
I want to pass coffType to coffeeName and numbag to numberOfBag. How can i change these values?

In CoffeClass create a constructor that receives the parameter that you want to set:
public Coffee(String coffeeName, double amountPay, int numberOfBag) {
this.coffeeName = coffeeName;
this.amountPay = amountPay;
this.numberOfBag = numberOfBag;
}
In MenuClass you will instantiate the object Coffe with the selected values by the user:
Coffe coffeOne = new Coffe(coffeName, amoutPay, numBag);
In the same class use the object to get the discount:
double discountCoffeOne = coffeOne.getDiscount();
You're done.
You use the CoffeClas as a model to an object with the values that you want. That way you can have a lot of different coffe just instantiating another Coffe with another name and using it.
When needed you should use getters and setters to change the attributes of an object, when needed means you should not create them when the values are not supposed to change or the other classes should not have permission to change these attributes.
public setCoffeeName(String coffeeName){
this.coffeeName = coffeName
};
public getCoffeeName(){
return coffeName;
}
;)
Oh, and just like azro said:
"Please follow conventions, and start naming attributs/variables with lowercase"

Here, inorder to pass the value of CoffType to CoffeeName and NumBag to NumberOfBag we can either use a parameterized constructor or setters. Both ways we can pass the value from Menu class to Coffee class.
Using parameterized constructor
create parameterized constructor in the Coffee class and instantiate the Coffee class from the Menu class.
Setter
create 2 setters to set each of NumberOfBag and CoffeName in the Coffee class and set the value by instatiating Coffee class and setting the value to both.

Related

When I type sbi(caps lock off), I am getting result of both if statement and else statement. How can get only result of if statement?

This is my scenario: Bank is a class that provides functionality to get rate of interest. However, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% as a rate of interest.
class bank{
public String name;
int interest(){
return 0;
}
String name(){
name = "bank";
return name;
}
}
//SBI Bank
class SBI extends bank {
int interest() {
return 8;
}
public String name() {
String name;
name = "SBI";
return name;
}
}
//ICICI Bank
class ICICI extends bank {
int interest() {
return 7;
}
String name() {
String name;
name = "ICICI";
return name;
}
}
//Axis Bank
class AXIS extends bank {
int interest() {
return 9;
}
String name() {
String name;
name = "AXIS";``
return name;
}
}
/*Main Class*/
public class head {
public static void main(String args[]) {
String n;
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Enter the bank name");
java.util.Scanner sc = new java.util.Scanner(System.in);
n = sc.next();
/*Conditional Statements*/
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}
if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}
if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
}
}
There are several serious problems here. The one that is troubling you right now is that you don't use else if between your if statements that are supposed to be mutually exclusive. Fixing that would solve your immediate problem.
But the name field of the subclasses is never set. It will be null, unless at some point you manage to call the name() method of the bank base class. That method sets the field to "bank".
To be clear, the subclasses are not setting the name field because in the name() method you have a local variable name which shadows the field.
public String name() {
String name; // this local variable shadows the "name" field
name = "SBI"; // this sets the local variable; the field remains null
return name;
}
One way you could end up calling the name() method of the base class is:
bank b = new SBI();
System.out.println(b);
Even though it's an SBI objects, it calls the method of the base class because the variable is declared to be a bank, not an SBI.
This will print bank and now the name field of that SBI object will be set to "bank", although if you call its name() method, it will still return "SBI". But if you access its name field, you'll see it's "name":
System.out.println(b.name());
System.out.println(b.name);
This will print SBI and then name. This is a recipe for disaster. Finally, I will just note that the name field is public which can lead to further problems, and you are not following the normal Java naming convention that class names start with an upper case letter, fields and variables start with a lower case letter, and constants are in all caps. In particular, class bank should be named Bank. Not following standard naming conventions makes your code harder for other programmers to read and makes it less likely that you'll get help here with your program.
You need to rethink your design. The field should either be protected and set in the constructor, or you should get rid of the field and just return a constant from the name() method, at which point Bank could just be an interface with name() and interest() methods instead of a class. (Or return the name from the toString() method, and make Bank a functional interface (an interface with just one abstract method.)) Finally, you need to use else if for a chain of mutually exclusive if conditions.
Your code is returning the print statement in else because that else is for the last if conditional statement ONLY, that's
if (n.equalsIgnoreCase(a.name()))
It is executing the else block because SBI does not equal a.name
To fix that. You should do this
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}else
if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}else
if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
Although this will solve your problem, I will advice you use switch statement.
USe Else IF Condition and Remembr to Make Vehicle class Abstract
abstract class bank{
public String name;
abstract int interest();
abstract String name();
}
//SBI Bank
class SBI extends bank {
int interest() {
return 8;
}
public String name() {
String name;
name = "SBI";
return name;
}
}
//ICICI Bank
class ICICI extends bank {
int interest() {
return 7;
}
String name() {
String name;
name = "ICICI";
return name;
}
}
//Axis Bank
class AXIS extends bank {
int interest() {
return 9;
}
String name() {
String name;
name = "AXIS";
return name;
}
}
/*Main Class*/
public class Demo {
public static void main(String args[]) {
String n;
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Enter the bank name");
java.util.Scanner sc = new java.util.Scanner(System.in);
n = sc.next();
/*Conditional Statements*/
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}
else if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}
else if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
}
}

Applying two different sets of interest rates to two objects of the same class

How can I make two objects of the same class use different interest rates?
I need to make it so that savingAccount2 and savingAccount3 use different interest rates.
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
These objects both inherit from a class called Account.java. This superclass contains all the methods that include how to calculate the interest.
Here is the current method in the superclass that calculates the 1 year interest account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
Here is the button that triggers this method:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
Currently I am using variables with double values assigned to them, but of course this means that both objects(savingAccount2 and savingAccount3) use the same numbers. Note that these variables are stored in the Account.java superclass Like so:
public double lowRate = 0.019;
public double highRate = 0.025;
I think I may need to use a constructor for each object, with pre-set values to solve my issue but I don't understand how to implement that idea. Any suggestions?
You can write method in class Account to set the values of lowRate and highRate like:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
Now when you create an object of class SavingsAccount, you can do:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
Just do it:
savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);
in class definition:
savingAccount1UI(float lowRate,float highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
when computing pass also the class to the method and access the inners value.
public void interest(double interest,savingAccount1UI account){
if(balance<target){
interest = balance*account.lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*account.highRate;
balance = balance + interest;
}
updatebalance();
}
It seems you are looking for this:
public class Account {
private double lowRate;
private double highRate;
//other fields
public Acount(double lowRate, double highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
// your interest() method
// getters & setters
}
public class SavingAccount1UI extends Account {
public SavingAccount1UI(double lowRate, double highRate) {
super(lowRate, highRate);
}
// rest of your stuff
}
This way you are only able to create an object passing the values you need, like:
SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);
Now every time you call your interest() method, it will take into consideration the values passed.

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Java Inheritance Demonstration - on user input and incompatible types

I'm almost done with a Java program but I'm having a snag compiling.
This program is a demonstration on inheritance, with 4 classes (including a driver) but I'm getting 4 errors on the aforementioned driver. I also have a problem with making the program general (as to allow user input) as the data I'm trying to read in are of different types. I think I need to use valueOf somewhere, but we haven't gotten that far in my class. I apologize for the length.
Here are the specifications:
Define a class named
Payment
that
contains an instance variable of type
double
that stores the
amount of the payment and appropriate accessor and mutator methods.
Also create a method
named
paymentDetails
that outputs an English sentence to describe the amount of the payment.
Next, defi
ne a class named
CashPayment
that is derived from
Payment.
This class should
redefine the
paymentDetails
method to indicate that the payment is in cash. Include appropriate
constructor(s).
Define a class named
CreditCardPayment
that is derived from
Payment
.
This class should
contain instance variables for the name on the card, expiration date, and credit card number.
Include appropriate constructor(s). Finally, redefine the
paymentDetails
method to include all
credit card information in the printout.
Create main method that creates at least two
CashPayment
and two
CreditCardPayment
objects with different values and calls
paymentDetails
for each.
Be sure to make the program general so that a user can enter data!!!
Here is one of the error messages:
C:\Program Files\Java\jdk1.8.0_60\bin\ghp3driver.java:21: error: incompatible types: String cannot be converted to Payment
and here is the code...
import java.util.*; //new file/class
class ghp3driver {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
Payment cash1 = user_input.next();
Payment cash2 = user_input.next();
Payment credit1 =
user_input.next();
Payment credit2 =
user_input.next();
System.out.println("Cash 1 details:");
cash1.paymentDetails();
System.out.println();
System.out.println("Cash 2 details:");
cash2.paymentDetails();
System.out.println();
System.out.println("Credit 1 details:");
credit1.paymentDetails();
System.out.println();
System.out.println("Credit 2 details:");
credit2.paymentDetails();
System.out.println();
}
}
import java.util.*; //NEW FILE/CLASS
public class Payment {
private double amount;
public Payment() { //constructor
amount = 0.0;
}
public Payment(double paymentAmount) { //initializes payment amount
amount = paymentAmount;
}
public void setPayment(double paymentAmount) {
amount = paymentAmount;
}
public double getPayment() {
return amount;
}
public void paymentDetails() {
System.out.println("The payment amount is " + amount);
}
}
class CreditCardPayment extends Payment {
private String date, name, ccn;
public CreditCardPayment(double amount, String date, String name, String ccn) {
super(amount);
this.date = date;
this.name = name;
this.ccn = ccn;
}
public void paymentDetails() { //printing
System.out.println("Name on card: " + this.getName());
System.out.println("Expiration date: " + this.getDate());
System.out.println("Credit card number: " + this.getCcn());
System.out.println("The payment by credit card amount is " + getPayment());
}
public String getCcn() {
return ccn;
}
public void setCcn(String ccn) {
this.ccn = ccn;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class CashPayment extends Payment {
public CashPayment(double paymentAmount) {
super(paymentAmount);
}
public void paymentDetails() {
System.out.println("The payment cash amount is " + this.getPayment());
}
}
Your statements
Payment cash1 = user_input.next( );
Payment cash2 = user_input.next( );
Payment credit1 =
user_input.next( );
Payment credit2 =
user_input.next( );
You cannot assign a string value to a different class
Correct usage would be something like below
Payment cash1 = new Payment();
Payment cash2 = new Payment();
Payment credit1 = new Payment();
Payment credit2 = new Payment();
cash1.setPayment(new Double(user_input.next( )));
cash2.setPayment(new Double(user_input.next( )));
credit1.setPayment(new Double(user_input.next( )));
credit2.setPayment(new Double(user_input.next( )));
Also your code has a warning "Resource leak: 'user_input' is never closed"
You need to work this one out.
My suggestion you need to study Java programming language more before you start putting questions to correct your code. Your are missing basic points which are very important.

What the methods do which starts with getXXXX()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have to use these two methods in my program but I have no idea what they do because my program works the way I want it to without these and when I put them in my code it doesn't make a difference in the output or anything.
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
Here is the rest of my code:
public class GroceryListIU extends javax.swing.JFrame {
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
public double itemPrice;
public final double SALES_TAX = 0.065;
public double totalPrice;
public double tax;
public double purchase;
public int numItems;
/**
* Creates new form GroceryListIU
*/
public GroceryListIU() {
initComponents();
//delcares purchase and numItems and resets them to 0
purchase = 0;
numItems = 0;
}
//set method to add item price
public void recordPurchase(double itemPrice) {
purchase = purchase + itemPrice;
numItems++;
}
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
//clicking exit ends the program
System.exit(0);
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
//When the user clicks "reset" all variables are set to blank or 0
txtItemPrice.setText("");
txtSubTotal.setText("");
txtNumberOfItems.setText("");
txtSalesTax.setText("");
txtTotalPrice.setText("");
numItems = 0;
purchase = 0;
}
private void btnCheckoutActionPerformed(java.awt.event.ActionEvent evt) {
boolean keepShopping = true;
JFrame frame = new JFrame();
while (keepShopping) {
try {
//When the user clicks "checkout" a input dialog will appear to enter the item price
String newItemPrice = JOptionPane.showInputDialog(frame,
"Enter Item Price",
"Enter Price",
JOptionPane.PLAIN_MESSAGE);
//if the user clicks cancel or clicks OK and left the text field blank, calculations will be made
if ((newItemPrice != null) && (newItemPrice.length() > 0)) {
//parse the double item price
itemPrice = Double.parseDouble(newItemPrice);
//takes itemPrice and plugs it into recordPurchase method
recordPurchase(itemPrice);
//adds 1 to txtNumberOfItems each time the user enters a number until it ends
txtNumberOfItems.setText((numItems) + "");
//adds item price to the txtItemPrice text field
txtItemPrice.setText(defaultFormat.format(itemPrice));
//adds the sub total to the txtSubTotal text field
txtSubTotal.setText(defaultFormat.format(purchase));
} else {
//when the user clicks ok when blank or cancel the program does the rest of the calculations
keepShopping = false;
//tax is 6.5%, you would multiply that by the purchase total
tax = SALES_TAX * purchase;
//sets "tax" in the txtSalesTax text field
txtSalesTax.setText(defaultFormat.format(tax));
//the total price is tax plus the sub total
totalPrice = tax + purchase;
//add the total price to the totalPrice text field
txtTotalPrice.setText(defaultFormat.format(totalPrice));
}
} catch (NumberFormatException e) { //if the user enters string data, an error will appear
JOptionPane.showMessageDialog(frame,
"You must enter positive numerical data!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
}
}
}
How do I use them in my program?
Therese are getters. You might have them on your program, but you never used them.
Note that they are public, while the variables they return should have been private. You're breaking encapsulation by exposing your data members.
Consider this class:
public class MyClass {
private int myPrivateInt;
private String myPrivateString;
public int getInt() {
return myPrivateInt;
}
public String getString() {
return myPrivateString;
}
}
Since myPricateInt and myPrivateString are private, you can't access them from outside, that's why I need a getter method to get these variables.
They are getters
The point of getters and setters is that only they are meant to be used to access the private varialble, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Short and sweet advantages are
For Re-usability.
To perform Validation in later stages of programming.
Getter and setter methods are public interfaces to access private
class members
As per ur Q
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
purchase and numItems are private, so u need getters
This is encapsulation.
If you have getters like these, then private access modifiers on your fields would make them more meaningful.
private double purchase;
private int numItems;
Silly Question.
Those are getter methods for the variables purchase and nemItems, which are private .
Accessors and Mutators in Java. Does it ring a bell.
They are set and get methods. Public double getPurchase() returns the purchase variable from the class and public int getItems() returns the numItems variable. The reason it doesn't affect your code when you remove them is because you are accessing those variables directly because they are public. You would have to use those methods if you had your variables set to private.

Categories