How can i set the result of a method in a toString - java

I want to display the result of a method in my ToString, how can I do that?
here is my code so far:
you can see at the bottom line that I don't know what to write for getting the result of the "updatedPrice", can u help?
public double updatedPrice(double price){
this.price=price;
double ChangePriceRate, ChangePriceAmount, finalPrice;
if(name=="Bamba"){
ChangePriceRate = 0.15;
}else{
ChangePriceRate = 0.05;
}
ChangePriceAmount = price * ChangePriceRate;
if(name=="Bamba"){
finalPrice = price + ChangePriceAmount;
}else{
finalPrice = price - ChangePriceAmount;
}
}
public String toString (){
return "Name of the Snack: "+name+ "\n"+
"Name of the Company: "+comp+ "\n"+
"Price before discount: "+this.price+ "\n"+
"Price after discount: "+ **finalPrice?** + "\n";
}
b.t.w - I'm really new to this, a total begginer.**
thank you.

Just call your method there:
public String toString (){
return "Name of the Snack: " + name + "\n" +
"Name of the Company: " + comp + "\n" +
"Price before discount: " + this.price+ "\n" +
"Price after discount: " + updatedPrice(this.price) + "\n";
}
Attention:
Generally I would advise AGAINST calling methods in the toString() method.
It would be better if you only show the state of the class inside toString() and therefore only show the values of existing fields.
This means in consequence that you should introduce a field called finalPrice and store your value there.
After that you can show this value using the toString() method:
public static class MyClass {
private String name;
private String comp;
private double price;
private double finalPrice; // <-- Field for final price
[...]
public void updatePrice(double price) {
this.price = price;
double changePriceRate;
double changePriceAmount;
if ("Bamba".equals(this.name)) { // <-- Use equals()!
changePriceRate = 0.15;
} else {
changePriceRate = 0.05;
}
changePriceAmount = price * changePriceRate;
if ("Bamba".equals(this.name)) { // <-- Use equals()!
finalPrice = price + changePriceAmount;
} else {
finalPrice = price - changePriceAmount;
}
}
public String toString() {
return "Name of the Snack: " + name + "\n" +
"Name of the Company: " + comp + "\n" +
"Price before discount: " + price + "\n" +
"Price after discount: " + finalPrice + "\n";
}
}
Bonus point:
Do not use == for comparing strings, use equals() instead if you want to compare the contents of strings!

create a property finalPrice and assign the value to
this.finalPrice = /*the price*/
and your code will work

store the finalPrice variable as an instance variable:
double finalPrice;
public double updatedPrice(double price){
this.price=price;
double ChangePriceRate, ChangePriceAmount;
if(name=="Bamba"){
ChangePriceRate = 0.15;
}else{
ChangePriceRate = 0.05;
}
ChangePriceAmount = price * ChangePriceRate;
if(name=="Bamba"){
finalPrice = price + ChangePriceAmount;
}else{
finalPrice = price - ChangePriceAmount;
}
return finalPrice;
}
public String toString (){
return "Name of the Snack: "+name+ "\n"+
"Name of the Company: "+comp+ "\n"+
"Price before discount: "+this.price+ "\n"+
"Price after discount: "+ finalPrice + "\n";
}
and another hint: name variables always with a lowercase letter at the beginning, it helps you to differentiate between class names and variable names.

Related

I m creating a cashier class but i cannot get name and price of each item to display

I was asked to create a cashier, testcashier and get data java classes to mimic a simple cashier operation. I created all the classes and everything including making and displaying change works but the items names and prices are not being displayed, why?
public class Cashier {
private int numberOfItems;
private double totalSum;
private double amount;
private String names;
private String s, name;
private double price, tendered, change, dollars, quarters, dimes,
nickels, pennies;
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
public Cashier(){
this.name = "";
this.price = price;
price = 0;
this.s = "";
}
public Cashier(String name, double price, String s)
{
//this.tendered = 0;
this.name= name;
this.price = price;
//amount = tendered;
//price = 0;
//this.s = s;
}
public double average()
{
return totalSum/numberOfItems;
}
public void add(String name, double price)
{
totalSum = totalSum + price;
s = s + name + "........" + price + "\n";
numberOfItems++;
}
public void makeChange()
{
change = amount - totalSum;
change = 100 * change;
change = Math.round(change);
change = change / 100;
dollars = (int)(amount - totalSum) * 100 / 100;
pennies = (int)(change * 100) % 100;
quarters = (int)pennies / 25;
pennies = (int)pennies % 25;
dimes = (int)pennies / 10;
pennies = (int)pennies % 10;
nickels = (int)pennies / 5;
pennies = (int)pennies % 5;
pennies = (int)pennies;
}
public String getNames()
{
return name;
}
public double getPrices()
{
return price;
}
public double getTotal()
{
return totalSum;
}
public double getMoney()
{
return tendered;
}
public double getChange()
{
return tendered - totalSum ;
}
public double getQuantity()
{
return numberOfItems;
}
public double getAverage()
{
return average();
}
public double getDollars()
{
return dollars;
}
public double getQuarters()
{
return quarters;
}
public double getDimes()
{
return dimes;
}
public double getNickels()
{
return nickels;
}
public double getPennies()
{
return pennies;
}
public void tendered(double amount)
{
// double tendered;
tendered = amount;
}
}
public class TestCashier {
public static void main(String[] args) {
Cashier c = new Cashier();
String name = GetData.getWord("Enter name of item");
double price = GetData.getDouble("Enter price of item");
c.add(name, price);
name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);
name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);
// Add a two more entries of your own
// Now average the price of the items
c.average();
// Make payment
double amount = GetData.getDouble("Enter amount of money for payment");
c.tendered(amount);
//ndered(amount); // Twenty dollars were tendered
c.makeChange();
generateReceipt(c);
}
public static void generateReceipt(Cashier c)
{
String s= "ABC Groceries Shop \n";
s = s + "Welcome – thanks for stopping, \n";
DateFormat df = DateFormat.getDateInstance();
Date d = new Date();
NumberFormat f = NumberFormat.getCurrencyInstance();
s = s + "Today is " + df.format(d) + "\n";
s = s + "Item:" +(c.getNames());
//\n";
s = s + c.getNames() + "..... " + f.format(c.getPrices()) + "\n" + c.getNames() +
"..... " + f.format(c.getPrices()) + "\n" + c.getNames() + "....." +
f.format(c.getPrices()) + "\n";
s = s + "____________________" + "\n";
s = s + "Total " + f.format(c.getTotal()) + "\n\n";
s = s + "Amount tendered " + f.format(c.getMoney()) + "\n";
s = s + "The change is " + f.format(c.getChange()) + "\n";
s = s + "There were " + c.getQuantity() + " items" + "\n";
s = s + "The average price is " + f.format(c.getAverage()) + "\n\n";
s = s + "The change includes :" + "\n";
s = s + c.getDollars() + " dollars" + "\n" + c.getQuarters()+ " quarters" +
"\n" + c.getDimes()+ " dimes" + "\n" + c.getNickels()+ " nickels" +
"\n" + c.getPennies() + " cents";
JTextArea text = new JTextArea(s,15, 25);
JScrollPane pane = new JScrollPane(text);
JOptionPane.showMessageDialog(null,pane, "Your bill",
JOptionPane.INFORMATION_MESSAGE);
}
}
public class GetData {
static String str;
static double getDouble(String s)
{
str = JOptionPane.showInputDialog(s);
return Double.parseDouble(str);
}
static int getInt(String s)
{
str = JOptionPane.showInputDialog(s);
return Integer.parseInt(str);
}
static String getWord(String s)
{
//str = JOptionPane.showInputDialog(s);
return JOptionPane.showInputDialog(s);
}
}
Your public void add(String name, double price) method concatenates the names and prices to the s member of the Cashier class, but you print the output of the getNames() and getPrices() methods, which return members that remain empty.
One way to get the output you want is to call a method that returns s and print it.
You need to instantiate Cashier using the contructor
public Cashier(String name, double price, String s)
as in
Cashier c = new Cashier (name, price, "");
not
c.add (name, price);
which does not set the field's values

Why is the negative sign printing before the $ sign?

I am supposed to add a toString method to the banckAccount class.
It should return a name separated by a comma and a space. Ex: "Yana" and balance of 3.03 , the call yana.toString() should return the string "Yana, $3.03".
I tried to add:
public String toString() {
return name + ", " + "$"+ balance;
}
It works when I type in:
"user, $90.01"
But when I enter
"Bankrupt Government, -$765432.10"
I keep getting:
"Bankrupt Government, $-765432.1"
Code:
import java.util.*;
public class BankAccount {
String name;
double balance;
public void deposit (double amount ){
balance = balance + amount;
}
public void withdraw ( double amount) {
balance = balance - amount ;
}
}//end of class
Your answer is right here:
return name + ", " + "$"+ balance;
Java simply concatenates the string as you have defined it. So if balance is a negative number, you will get $, followed by a negative number.
If you want it to display the - in the proper place, you can do something like this:
String sign = (balance < 0) ? "-" : "";
System.out.println(name + ", " + sign + "$" + Math.abs(balance));
Your balance is negative so it prints as listed. It needs to be
if(balance < 0){
balance = balance * -1;
return name + ", " + "-$"+ balance;
}
else{
return name + ", " + "$"+ balance;
}
It is quite obvious, what your method toString() is doing. If balance is negative, it is just added to the string with "-" sign after the "$". I would detect, if the balance is positive or not:
private String toString() {
if (balance > 0.0) {
return name + ", " + "$" + balance;
} else {
return name + ", -$" + (balance * (-1));
}
}
Or
private String toString() {
return name + ", " +
balance > 0.0 ? ("$" + balance) : ("-$" + (balance * (-1)));
}
hope this helps run this program
import java.util.*;
import java.io.*;
public class HelloWorld{
public String toString() {
if(balance<0)
{
balance= Math.abs(balance);
return name + ", " +"-"+ "$"+ balance;
}else
{
return name + ", " + "$"+ balance;
}
}
String name="sachin";
double balance=-1000.00;
public void deposit (double amount ){
balance = balance + amount;
}
public void withdraw ( double amount) {
balance = balance - amount ;
}
public static void main(String []args){
// System.out.println("Hello World");
HelloWorld helloWorld = new HelloWorld();
System.out.println(helloWorld.toString());
}
}

Java project returning null values

Hi I am new to Java programming. Why are my values returning null after I enter them on the input dialog. I have two classes, one called VehicleApp and the other called VehicleFactory. Help would be appreciated. Thanks.
Full code VehicleApp.java
package romprojectname;
import java.text.NumberFormat;
import javax.swing.JOptionPane;
public class VehicleApp{
public static void main(String[] args) {
String firstname = JOptionPane.showInputDialog("Enter your first name");
String lastname = JOptionPane.showInputDialog("Enter your last name");
long phone = Long.parseLong(JOptionPane.showInputDialog("Enter your phone"));
int nbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter number of vehicles"));
int nbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter number of tanks"));
VehicleFactory vehicleObject = new VehicleFactory();
vehicleObject.getSummary();
vehicleObject.HayloFactory(firstname, lastname, phone, nbrVehicles, nbrTanks);
vehicleObject.calcFuelTankCost();
vehicleObject.calcManufacturingCost();
vehicleObject.calcSubtotal();
vehicleObject.calcTax();
vehicleObject.calcTotal();
}
}
Full code VehicleFactory.java
package romprojectname;
import java.text.NumberFormat;
import javax.swing.JOptionPane;
public class VehicleFactory{
private String firstname;
private String lastname;
private Long phone;
private int nbrVehicles =0;
private int nbrTanks =0;
private double manufactureCost =0;
private double fuelTankCost =0;
private double subtotal =0;
private double tax =0;
private double total = 0;
private final double VEHICLE_PRICE = 500.19;
private final double FUELCELL_PRICE = 2.15;
private final int CELLS_PER_TANK = 12;
private final double taxrate = 7.25 / 100 ;
public void HayloFactory(String firstname, String lastname, Long phone, int nbrVehicles, int nbrTanks){
this.firstname = firstname;
this.lastname = lastname;
this.phone = phone;
this.nbrVehicles = nbrVehicles;
this.nbrTanks = nbrTanks;
}
public void calcManufacturingCost(){
double manufactureCost = nbrVehicles * VEHICLE_PRICE;
}
public void calcFuelTankCost(){
double fuelTankCost = nbrVehicles * nbrTanks * CELLS_PER_TANK * FUELCELL_PRICE;
}
public void calcSubtotal(){
double subtotal = manufactureCost + fuelTankCost;
}
public void calcTax(){
double tax = subtotal * taxrate;
}
public void calcTotal(){
double total = subtotal + tax;
}
NumberFormat cf = NumberFormat.getCurrencyInstance();
public void getSummary(){
String summary = "WELCOME TO HAYLO MANUFACTURING" + "\n" + "\n";
summary += "Customer Name: " + firstname + " " + lastname + "\n";
summary += "Customer Phone: " + phone + "\n";
summary += "Number of Vehicles: " + nbrVehicles + "\n";
summary += "Number of Tanks: " + nbrTanks + "\n";
summary += "Vehicle Cost ($500.19 / vehicle): " + cf.format(manufactureCost) + "\n";
summary += "Tanks Cost ($2.15 / fuel cell): " + cf.format(fuelTankCost) + "\n";
summary += "Subtotal: " + cf.format(subtotal) + "\n";
summary += "Tax (7.25%): " + cf.format(tax) + "\n";
summary += "Total: " + cf.format(total) + "\n";
//display the summary
JOptionPane.showMessageDialog(null, summary);
}
}
Problem (code taken from VehicleFactory.java)
All of the summaries such as customer name are returning null values and all the costs and totals are $0.00.
public void getSummary(){
String summary = "WELCOME TO HAYLO MANUFACTURING" + "\n" + "\n";
summary += "Customer Name: " + firstname + " " + lastname + "\n";
summary += "Customer Phone: " + phone + "\n";
summary += "Number of Vehicles: " + nbrVehicles + "\n";
summary += "Number of Tanks: " + nbrTanks + "\n";
summary += "Vehicle Cost ($500.19 / vehicle): " + cf.format(manufactureCost) + "\n";
summary += "Tanks Cost ($2.15 / fuel cell): " + cf.format(fuelTankCost) + "\n";
summary += "Subtotal: " + cf.format(subtotal) + "\n";
summary += "Tax (7.25%): " + cf.format(tax) + "\n";
summary += "Total: " + cf.format(total) + "\n";
//display the summary
JOptionPane.showMessageDialog(null, summary);
You haven't really described the problem, but I suspect this is the cause:
VehicleFactory vehicleObject = new VehicleFactory();
vehicleObject.getSummary();
vehicleObject.HayloFactory(firstname, lastname, phone, nbrVehicles, nbrTanks);
You're calling getSummary before you call HayloFactory - so it's trying to display the values in the object before you've set them to useful values.
Additionally, all your calcXyz methods are introducing new local variables, like this:
public void calcTotal(){
double total = subtotal + tax;
}
Instead, they should be setting the field values:
public void calcTotal(){
total = subtotal + tax;
}
If you change all of your calculation methods appropriately, then move the getSummary() call to the very end, it will work. (It's not quite how I'd have written the code, but that's a different matter.)
The variables defined insides your methods have local scope only for example
double manufactureCost = nbrVehicles * VEHICLE_PRICE; it actually hides your class variable manufactureCost .. they should be instead used as
manufactureCost = nbrVehicles * VEHICLE_PRICE;
This way you can actually set the class variable which in turn displayed inside your getSummary method

Java - How to print values to 2 decimal places

I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!
import java.util.Scanner;
public class Team {
public String name;
public String location;
public double offense;
public double defense;
public Team winner;
public Team(String name, String location) {
this.name = name;
this.location = location;
this.offense = luck();
this.defense = luck();
}
public double luck() {
return Math.random();
}
Team play(Team visitor) {
Team winner;
double home;
double away;
home = (this.offense + this.defense + 0.2) * this.luck();
away = (visitor.offense + visitor.defense) * visitor.luck();
if (home > away)
winner = this;
else if (home < away)
winner = visitor;
else
winner = this;
return winner;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter name and location for home team (on separate lines)");
String homeName = s.next();
String homeLocation = s.next();
Team homeTeam = new Team(homeName, homeLocation);
System.out.println("Enter name and location for home team (on separate lines)");
String awayName = s.next();
String awayLocation = s.next();
Team awayTeam = new Team(awayName, awayLocation);
Team winnerTeam = homeTeam.play(awayTeam);
System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}

toString method not printing out my object, instead it's printing the memory adress [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
BankAccount b0, b1, b2, b3;
b1=new BankAccount();
b2=new BankAccount();
b3=new BankAccount();
for (int i=0; i<3; i++)
{
if (i==0)
b0=b1;
else if (i==1)
b0=b2;
else
b0=b3;
and (what you just saw was part of the demo, below is part of the class stuff)
public String toString(double deposit, double withdraw, double fee, double total) {
String str=name+"'s bank account statement:" + "\nInitial balance: " + balance +
"\nDeposit amount: " + deposit + "\nWithdraw amount: " + withdraw + "\nNumber of transactions: "
+ transac + "\nTotal bank fees: " + fee + "Final monthly balance: " + total;
return str;
and (demo, I haven't included all the code, just because this is still an open assignment.
System.out.println(b0);
I really have no clue why it's not printing the string stuff :(
all of the class (will remove later)
public class BankAccount {
private String name;
private double balance;
private int transac;
public BankAccount() {
balance=0;
}
public void setName(String accountName) {
name=accountName;
}
public void setBalance(double accountBalance) {
balance=accountBalance;
}
public void setTransac(int accountTransac) {
transac=accountTransac;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public int getTransac() {
return transac;
}
public double getDeposit(double deposit) {
return balance+deposit;
}
public double getWithdraw(double deposit, double withdraw) {
return balance+deposit-withdraw;
}
public double getFee(double fee, int accountTransac, double deposit, double withdraw) {
fee=10;
if (transac<20)
fee+=transac*0.5;
else if (20<=transac && accountTransac<40)
fee+=transac*0.25;
else if (40<=transac && transac<60)
fee+=transac*0.2;
else
fee+=transac*0.1;
if (balance+deposit-withdraw<400)
fee+=15;
return fee;
}
public double finalBalance(double fee, int accountTransac, double deposit, double withdraw) {
double total=balance+deposit-withdraw-fee;
return total;
}
public String toString(double deposit, double withdraw, double fee, double total) {
toString(this.deposit, this.withdraw, this.fee, this.total);
String str=name+"'s bank account statement:" + "\nInitial balance: " + balance +
"\nDeposit amount: " + deposit + "\nWithdraw amount: " + withdraw + "\nNumber of transactions: "
+ transac + "\nTotal bank fees: " + fee + "Final monthly balance: " + total;
return str;
}
}
you should override public String toString() method (without arguments):
if you already have method public String toString(double deposit, double withdraw, double fee, double total) then use this:
class BankAccount {
public String toString() {
toString(this.deposit, this.withdraw, this.fee, this.total);
}
/* .. */
You've overloaded the toString() method, providing a sibling with a different set of arguments.
You want to override the toString() method without arguments.
For example, if all the arguments to your other toString() method were member fields:
public String toString() {
String str=name+"'s bank account statement:" + "\nInitial balance: " + balance +
"\nDeposit amount: " + deposit + "\nWithdraw amount: " + withdraw + "\nNumber of transactions: "
+ transac + "\nTotal bank fees: " + fee + "Final monthly balance: " + total;
return str;
}
The piece of information that the other answers are missing that's important is that when you call System.out.println(b0) the java compiler is automatically inserting a call to .toString() - it's part of the language definition explained here.
Therefore, as said elsewhere, to print out an object you need to override this method.

Categories