Altering Setters and Getters Via User Input - java

I have tried a few things and I cannot seem to work this out. I'd like to keep a set price for the iPhone object that is defined by the latest user input.
Below is my Main class:
public class Main {
public static void main(String[] args) {
Iphone iphone = new Iphone();
iphone.setPrice();
System.out.println(iphone.getPrice());
}
}
Below is my Iphone class:
import java.util.Scanner;
public class Iphone {
//Class Attributes
private double price;
Scanner userInput = new Scanner(System.in);
//Constructer method
public Iphone(){
this.price = price;
}
//Getter Method
public double getPrice() {
return 0;
}
//Setter Method
public void setPrice() {
System.out.println("Enter a new price: ");
String price = userInput.nextLine();
System.out.println("The price has now been adjusted to " + price);
}
//toString
#Override
public String toString() {
return "Iphone{" +
"price=" + price +
'}';
}
}
Then, when I typed 800 into the console, instead of showing 800, it'll show 0.0, example below of how it prints to the console:
Enter a new price:
800 //what i typed in
The price has now been adjusted to 800
0.0
Now... I know it is because I am returning 0 in the getter method, so what do I return instead to get the desired result, as it's obviously going to print 0.0 but when I type return double userInput for example, that doesn't work. Note: I am still in the beginner stage of learning Java. Thank you in advance for any help given to me.

You need set class variable to input variable as this.price = Double.parseDouble(price)
public void setPrice() {
System.out.println("Enter a new price: ");
String price = userInput.nextLine();
this.price = Double.parseDouble(price);
System.out.println("The price has now been adjusted to " + price);
}

Your getPrice() method should return price field. And in setPrice() method you need to assign field price.

Related

Struggles in using multiple classes

So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.

Calorie Counter Java

I'm self-teaching myself Java and came across this question.
It required the making of multiple methods and also taking user data and making it into an array.
I am confused because wouldn't an array only have to be either a float, or a int or a double or a String, it cant be both a String and a double. But the user is entering multiple flavors of data. I am adding the question below and also the code I have scripted so far.
enter image description here
I have attached an image of the question
import java.util.Scanner;
public class salesRecord {
String Itemname;
int Quantity;
float unitPrice;
static float total;
String status; //for credit or debit
void data() {
Scanner input=new Scanner(System.in);
System.out.println("Enter your Item name: ");
Itemname=input.next();
System.out.println("Enter your Quantity: ");
Quantity=input.nextInt();
System.out.println("Enter your Unit Price: ");
unitPrice=input.nextFloat();
System.out.println("What is your Status: ");
status=input.next();
total=Quantity*unitPrice;
}
void ShowData() {
System.out.println("Item name is: "+Itemname);
System.out.println("Quantity is: "+Quantity);
System.out.println("Price per unit is: "+unitPrice);
System.out.println("Credit or Debit: "+status);
System.out.println("Total Price is: "+ total);
}
public static void main(String[] args) {
salesRecord cus1=new salesRecord();
Scanner inputcashier=new Scanner(System.in);
System.out.println("How many items do you have: ");
int items=inputcashier.nextInt();
for (int i = 0; i < items; i++) {
cus1.data();
cus1.ShowData();
total=total+total;
}
System.out.println("Your grand total is: "+total);
}
}
The problem states that you need to hold data of multiple types, an object is the best way to hold this data. You would first need to create the SalesRecord.
class SalesRecord{
String itemName;
double unitPrice;
double total;
String status;
// constructor
SalesRecord(String _itemName,double _unitPrice,double _total,String _status){
this.itemName = _itemName;
this.unitPrice = _unitPrice;
this.total = _total;
this.status = _status;
}
}
Once you have created this object the problem then states to store them in an array size 10 called salesRecord
SalesRecord[] salesRecord = new SalesRecord[10];
This array will now hold the SalesRecord objects. Thus has the type SalesRecord rather than your typical int,string or double.
Here's a good intro to creating and storing objects.

Java set method not working

Hello I'm new to programming and a first time poster here. I'm having trouble getting a Java application to display the correct values assigned via Set methods in a public class. Specifically the CreatePurchase application returns 0 for all 3 user defined variables (invoiceNumber, saleAmount, salesTax) which are Set in the Purchase public class.
Set and display the values here
public class Purchase
{
private int invoiceNumber;
private double saleAmount;
private double salesTax;
public int getInvoiceNumber()
{
return invoiceNumber;
}
public void setInvoiceNumber(int inv)
{
inv = invoiceNumber;
}
public double getSaleAmount()
{
return saleAmount;
}
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
public double getSalesTax()
{
return salesTax;
}
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax;
}
public static void displayPurchase(Purchase aPurch)
{
System.out.println("Purchase invoice number is " + aPurch.getInvoiceNumber() + "and the sale amount is " + aPurch.getSaleAmount() + "the taxable amount is " +aPurch.getSalesTax());
}
}
This is the CreatePurchase class that prompts the user for the variables and calls the method to display the values for the new object
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String args[])
{
Purchase aPurchase;
aPurchase = getPurchaseInfo();
Purchase.displayPurchase(aPurchase);
}
public static Purchase getPurchaseInfo()
{
Purchase tempPur = new Purchase();
int invoice;
double value;
double value2;
Scanner input = new Scanner(System.in);
System.out.println("Enter the invoice number:");
invoice = input.nextInt();
while(invoice < 1000 || invoice > 8000)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + invoice);
System.out.println("Please enter a whole number between 1000 and 8000");
invoice = input.nextInt();
}
tempPur.setInvoiceNumber(invoice);
System.out.println("Enter the amount of the sale:");
value = input.nextDouble();
value2 = (value * .05);
while(value < 0)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + value);
System.out.println("Please enter a non negative number");
value = input.nextDouble();
value2 = (value *.05);
}
tempPur.setSaleAmount(value);
tempPur.setSalesTax(value2);
return tempPur;
}
}
Any direction or advice on how to get the values entered to set and display properly would be greatly appreciated.
The setter needs to assign the new value to the instance field.
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
Yours do the opposite now, switch the assignment around:
public void setSaleAmount(final double sale)
{
this.saleAmount = sale;
}
You can also optionally add final to the parameter (since you don't intend to change it), and make it clear what the instance field is by using this.. Purely optional, but good practice, and in this case either addition would have resulted in a compile-time error to alert you of the mistake.
Your assignments are wrong(for the setters).
It should be salesTax that is set:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax; /* wrong assignment(for the purpose) */
}
And so on for your other class variables.
Remember: Setters and Getters are used to modify a class' variables.
All setters need to be modified as below:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
//tax = salesTax; <-- This line is wrong..
this.salesTax= tax ; // Change this line and it should work...
}
public void setInvoiceNumber(int inv)
{
//inv = invoiceNumber ; --> Invalid setting
this.invoiceNumber = inv; // Correct setting
}
public void setSaleAmount(double sale)
{
//sale = saleAmount; --> Invalid setting
this.saleAmount = sale; // Correct setting
}
Reason:
tax is local variable which is specific to the method setSalesTax.
salesTax is global variable for the object.
While setting value in your object, you need to set it/assign in the global variable salesTax
To avoid confusions, The best way to use a setter would be:
Object Class:
private double amount;
public void setAmount (double amount)
{
this.amount = amount;
}
It is because you do not set the new Value to your object value.
The correct way would be
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
salexTax = tax; //THIS is the mistake
}
Everytime you want to assign a value to an Object, Integer, or whatever, it goes from left to right. So, if you write:
int value=5;
int value2=10;
value2=value;
Value2 is 5 then.
Your setter method is wrong. You must use actual variable on LHS instead of formal argument.
for Ex, setInvoceNumber method should be like below :
public void setInvoiceNumber(int inv)
{
invoiceNumber = inv ;
}
Here inv is formal argument while invoiceNumber is actual variable which is going to store your value in object. You were assigning value of invoiceNumber to inv variable which has no effect in your code. Same goes for all your setter method.

Output user data to display class

package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.

Java code working on InventoryPart 2 program, have no idea what I am doing wrong?

I get the following error code:
C:\Documents and Settings\AdminUser\My Documents\InventoryPart2.java:83: class, interface, or enum expected
import java.util.*;
^
1 error
Tool completed with exit code 1
when compiling these source files:
public class Television { //class name and attributes
private String ItemNumber; //item # of product
private String ProductName; //product name
private double UnitsStock; //# of units in stock
private double UnitPrice; //Price per unit
private double InventoryValue; //The dollar value of the inventory in stock
private double CalculateInventory; //The total value of all of the inventory in stock
private double value;
//constructor
public Television (String item, String product, double units, double price) {
ItemNumber = item;
ProductName = product;
UnitsStock = units;
UnitPrice = price;
} //end constructor
//getter and setter methods for Television
public void setItemNumber (String item) { //setter for item number
this.ItemNumber = item;
} //end setter item number
public String getItemNumber() { //getter for item number
return ItemNumber;
} //end getter item number
public void setProductName (String product) { //setter for product name
this.ProductName = product;
} //end setter product name
public String getProductName() { //getter for product name
return ProductName;
} //end getter product name
public void setUnitsStock (double units) { //setter for units in stock
this.UnitsStock = units;
} //end setter units in stock
public double getUnitsStock() { //getter for units in stock
return UnitsStock;
} //end getter units in stock
public void setUnitPrice (double price) { //setter for unit price
this.UnitPrice = price;
} //end setter unit price
public double getUnitPrice() { //getter for unit price
return UnitPrice;
} //end getter for unit price
//calculate inventory value
public double getInventoryValue(){
return UnitsStock * UnitPrice;
}//end calculate inventory value
public void setCalculateInventory (double value){
this.CalculateInventory = value;
}
public double getCalculateInventory(){
double value = 0;
for(int i = 0; i < 5; i++){
value = getInventoryValue();
}
return value;
}
//end getter and setter methods for Television
} //end class Television
Main class:
import java.util.*;
public class InventoryPart2 {
public static void main (String args []){
//instantiate Television array
Television myTelevisions[] = new Television[5];
myTelevisions[0] = new Television ("0001", " Samsung UN46D6400",9,1599.99);
myTelevisions[1] = new Television ("0002", " Vizio XVT553SV",6,1299.00);
myTelevisions[2] = new Television ("0003", " Panasonic Viera TC-P50VT25",2,2079.99);
myTelevisions[3] = new Television ("0004", " Sony Bravia KDL-55EX720",8, 1889.99);
myTelevisions[4] = new Television ("0005", " LG Infinia 47LX9500",2,2099.00);
//output
for (int i = 0; i < myTelevisions.length; i++){
System.out.println("Product Number: \t\t" + myTelevisions[i].getItemNumber());
System.out.println("Product Name: \t\t\t" + myTelevisions[i].getProductName());
System.out.println("Number of Units in Stock: \t" + myTelevisions[i].getUnitsStock());
System.out.printf("Price per Unit: \t\t$%.2f\n", + myTelevisions[i].getUnitPrice());
System.out.printf("Value of Inventory: \t\t$%.2f\n", + myTelevisions[i].getInventoryValue());
System.out.println();
} // end output
for (int i = 0; i < 5; i++){ //output total inventory value
System.out.printf("Total Value of Inventory is: \t$%.2f\n", + myTelevision[i].getCalculateInventory());
System.out.println();
}//end output total inventory value
} //end method main
} //end class InventoryPart1
As #Greg and #EboMike stated, make sure you split your code in two files: Television.java and InventoryPart2.java.
Then, you have a typo here:
for (int i = 0; i < 5; i++){ //output total inventory value
System.out.printf("Total Value of Inventory is: \t$%.2f\n", + myTelevision[i].getCalculateInventory());
System.out.println();
}
It's myTelevision s[i].
If you fix what I'm telling you, your code runs fine... no worries. :)
EDIT:
I shouldn't be checking your code's logic here but if the last cycle is meant to compute the total inventory sum it should be something like this:
//output total inventory value
double total = 0.0;
for (int i = 0; i < 5; i++){
total += myTelevisions[i].getCalculateInventory();
}
System.out.printf("Total Value of Inventory is: \t$%.2f\n", total);
Is this all the same file? The import statement needs to go to the top.
The error message clearly shows you which line is causing a problem.
You've got a line
import java.util.*;
in the middle of your file. Java requires that import declarations go at the top of the file, before any class, interface, or enum declarations.
Two problems jump out at me:
As the error message says, you have an import statement out of place. Imports go at the top, after the package declaration and before the class declaration.
Assuming that the code you posted is in fact all in one file, you need to separate it into two files. You can't have two public classes in one .java file.

Categories

Resources