Java project returning null values - java

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

Related

Cant get this to run PAYROLL PROJECT java

package EmployeePayAppMRM;
import javax.swing.JOptionPane;
public class java
{
public static void main(String[] args)
{
String firstName;
String lastName;
String fullName;
String itemsSold;
String valueItems;
double basePay;
double totalPay;
double valueSold;
int numberSold;
final double ITEM_MIN = 10;
final int VALUE_MIN = 2500;
final int BONUS = 500;
firstName = JOptionPane.showInputDialog(" Enter employee's first name:");
lastName = JOptionPane.showInputDialog(" Enter employee's last name:");
fullName = JOptionPane.showInputDialog(" Enter base pay for " + firstName + " " + lastName + ":");
basePay = Double.parseDouble(fullName);
itemsSold = JOptionPane.showInputDialog(" Enter number of items sold for " + firstName + " " + lastName + ":");
totalPay = Double.parseDouble(fullName);
fullName = JOptionPane.showInputDialog(" Enter value of items sold for " + firstName + " " + lastName + ":");
valueSold = Double.parseDouble(fullName);
basePay = 1000;
if ( itemsSold > ITEM_MIN) //ERROR HERE (bad operand)
totalPay = (basePay + BONUS);
else if (valueSold >= VALUE_MIN)
totalPay = (basePay + BONUS);
else
totalPay = basePay;
System.out.println("this" + firstName + " " + lastName + " " + "will be paid" + totalPay "for selling" + itemsSold "items valued at $" + valueSold); //ERROR HERE
System.exit(0);
}
}
The first problem is about types, for the second you just miss some +
itemsSold is a String
ITEM_MIN is a double
Do like this, of parse it before
if(Double.parseDouble(itemsSold) > ITEM_MIN)
totalPay = (basePay + BONUS);
Finally, you don't need to define the variable and do the assignement later, just do it at the same time, once reoganisating all :
final double ITEM_MIN = 10;
final int VALUE_MIN = 2500;
final int BONUS = 500;
String firstName = JOptionPane.showInputDialog(" Enter employee's first name:");
String lastName = JOptionPane.showInputDialog(" Enter employee's last name:");
String fullName = JOptionPane.showInputDialog(" Enter base pay for " + firstName + " " + lastName + ":");
double itemsSold = Double.parseDouble(JOptionPane.showInputDialog(" Enter number of items sold for " + firstName + " " + lastName + ":"));
double valueSold = Double.parseDouble(JOptionPane.showInputDialog(" Enter value of items sold for " + firstName + " " + lastName + ":"));
double totalPay = 0;
double basePay = 1000;
if (itemsSold > ITEM_MIN) {
totalPay = (basePay + BONUS);
} else if (valueSold >= VALUE_MIN) {
totalPay = (basePay + BONUS);
} else {
totalPay = basePay;
}
System.out.println("this" + firstName + " " + lastName + " " + "will be paid" + totalPay + "for selling" + itemsSold + "items valued at $" + valueSold);

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

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.

Netbeans - Trying to get jCombobox selected item into another JFrame TextArea

Hello wonderful people!
I've relatively new to this java and I'm practicing by creating an online booking system with multiple JFrames (I've heard this could be an issue).
In short, I want to retrieve the value of this jComboBox and display it in a text area on a separate frame. The problem is: How do I undergo this?
private void filmSelecterActionPerformed(java.awt.event.ActionEvent evt) {
if (filmSelecter.getSelectedIndex() == 0)
continueButton.setEnabled(false);
else {
continueButton.setEnabled(true);
}
Second JFrame
private void jQty2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void reviewButtonActionPerformed(java.awt.event.ActionEvent evt) {
// -------Review Order Button----
double Qty1 = Double.parseDouble(jQty1.getText());
double Qty2 = Double.parseDouble(jQty2.getText());
double Qty3 = Double.parseDouble(jQty3.getText());
double Qty4 = Double.parseDouble(jQty4.getText());
double total, subTotal, ticket1, ticket2, ticket3, ticket4;
String adultPrice = String.format("%.2f", adultprice);
subTotal1.setText(adultPrice);
String studentPrice = String.format("%.2f", studentprice);
subTotal2.setText(studentPrice);
String childPrice = String.format("%.2f", childprice);
subTotal3.setText(childPrice);
String seniorPrice = String.format("%.2f", seniorprice);
subTotal4.setText(seniorPrice);
ticket1 = Qty1 * adultprice;
ticket2 = Qty2 * studentprice;
ticket3 = Qty3 * childprice;
ticket4 = Qty4 * seniorprice;
//subTotal
String sub1 = String.format("£%.2f", ticket1);
subTotal1.setText(sub1);
String sub2 = String.format("£%.2f", ticket2);
subTotal2.setText(sub2);
String sub3 = String.format("£%.2f", ticket3);
subTotal3.setText(sub3);
String sub4 = String.format("£%.2f", ticket4);
subTotal4.setText(sub4);
subTotal = ticket1 + ticket2 + ticket3 + ticket4;
// Total ticket price
String subTotalAll = String.format("£%.2f", subTotal);
jTotalPrice.setText(subTotalAll);
// Receipt
String Title = "\tGreenwich Peninsula Cinema\n\n\n";
String Movie = "Movie Name: " + "\n";
//String MovieDay = "Movie Day" + filmSelecter.getSelectedItem() + "\n";
String MovieTime = "Movie Time: \n";
String Barrier = "=========================================" + "\n";
String Adult = "Adult:" + subTotal1.getText() + "\nNumber of Tickets: " + Qty1 + "\n";
String Student = "Student:" + subTotal2.getText() + "\nNumber of Tickets: " + Qty2 + "\n";
String Child = "Child:" + subTotal3.getText() + "\nNumber of Tickets: " + Qty3 + "\n";
String Senior = "Senior:" + subTotal4.getText() + "\nNumber of Tickets: " + Qty4 + "\n";
String Thanks = "\n\n\tEnjoy the film!";
String ShowReceipt = Barrier + Title + Movie + /*MovieDay +*/ MovieTime + Barrier + Adult + Student + Child + Senior + Thanks + "\n" + Barrier;
filmReceipt.append(ShowReceipt);
}
I hope this helps in anyway.

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

No main methods, applets, or MIDlets found

When I run this a popup comes up telling me no main methods, applets, or MIDlets ound. Can someone tell me why please?--I am using jGrasp. I am trying to use main method and I haven't had this issue before.
import java.util.*;
import java.io.*;
public class ProgrammingExercise3.1
{
public static void main(String[] args);
{
double rectWidth;
double rectLength;
double radius;
int age;
double begBal;
char A;
String name;
double rate;
scanner inFile = new Scanner(new FileReader("C:\\Users\\sierr_000\\Desktop\\Sam School\\IT-145\\Exercises\\Ch 3\\inData.txt"));
PrintWriter outFile = new PrintWriter("C:\\Users\\sierr_000\\Desktop\\Sam School\\IT-145\\Exercises\\Ch 3\\outData.out");
rectWidth = inFile.next();
rectLength = inFile.next();
outFile.println("Rectangle: ")
outFile.println("Length = " + rectLength + ", width = " + rectWidth + ", area = "
+ (rectWidth*rectLength) + ", perimeter = " + (2 * (rectwidth + rectLengh)));
radius = inFile.next();
outFile.println("Circle: ");
outfile.println("Radius = " + radius + ", area = " + (radius*3.1416) + "Circumfrence = " + (2*3.1416*radius));
name = inFile.next();
age = inFile.next();
begBal = inFile.next();
rate = inFile.next();
outFile.println("Name: " + name + ", age: " + age);
outFile.printf("Beginning Balance: %7.2f" , begBal + "interest rate: %4.2f" , rate);
outFile.println("The character that comes after A in the ASCII is B");
inFile.close();
outFile.close();
}
}
This seems to be full of errors, but the main reason you are getting that error is that you put a semicolon after public static void main(String[] args).

Categories