Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
When I attempt to take in the users input and update the "Dexterity" variable, it only reflects in the following few lines of code. When I attempt to run the same command again, it doesn't reflect the previous input. For some reason It is not updating the variable accordingly.
public class SetAttributes {
public String userInput;
double Dexterity;
double Strength;
double Intelligence;
double Stamina;
double SkillPoints = 50;
public SetAttributes() {
this.SetDex(0);
this.SetStr(0);
this.SetInt(0);
this.SetSta(0);
this.SetSkillPoints(50);
}
public double GetSP(){
return SkillPoints;
}
public double GetDex() {
return Dexterity;
}
public void SetDex(double dexterity) {
this.Dexterity = dexterity;
}
public double GetStr(){
return Strength;
}
public double GetInt(){
return Intelligence;
}
public double GetSta(){
return Stamina;
}
public void SetStr(double strength){
this.Strength = strength;
}
public void SetInt(double intelligence){
this.Intelligence = intelligence;
}
public void SetSta(double stamina){
this.Stamina = stamina;
}
public void SetSkillPoints(double skillPoints) {this.SkillPoints = skillPoints;};
}
import java.util.Scanner;
public final class PointSpender {
public static void Spend() {
SetAttributes A = new SetAttributes();
System.out.println("Your current stats are ");
System.out.println("Strength " + A.Strength);
System.out.println("Stamina " + A.Stamina);
System.out.println("Intelligence " + A.Intelligence);
System.out.println("Dexterity " + A.Dexterity);
System.out.println("Please select the attribute you want to increase. You have " + A.SkillPoints + " available.");
Scanner Input = new Scanner(System.in);
A.userInput = Input.nextLine().toLowerCase();
if(A.userInput.charAt(0) == 'd'){
System.out.println("Dexterity");
System.out.println("Your Dexterity is " + A.Dexterity);
System.out.println("How many points in Dexterity?");
double Amount = Double.parseDouble(Input.nextLine());
A.SetDex(A.GetDex() + Amount);
// A.setDex(A.Dexterity + Amount);
System.out.println("You have put " + Amount + " into Dexterity" );
System.out.println("Your new dexterity is " + A.Dexterity);
}
}
}
Type "+" to spend your available skillpoints.
Type "Logout" to Log Out.
+
Your current stats are
Strength 0.0
Stamina 0.0
Intelligence 0.0
Dexterity 0.0
Please select the attribute you want to increase. You have 50.0 available.
d
Dexterity
Your Dexterity is 0.0
How many points in Dexterity?
45
You have put 45.0 into Dexterity
Your new dexterity is 45.0
+
Your current stats are
Strength 0.0
Stamina 0.0
Intelligence 0.0
Dexterity 0.0
Every time you invoke the static method "spend" you are creating a new instance of SetAttributes then you are blocking for user input. But before the block when the new instance is created all attributes of the new instance are set to 0.
This happens in your zero argument constructor, right here :
public SetAttributes() {
this.SetDex(0);
this.SetStr(0);
this.SetInt(0);
this.SetSta(0);
this.SetSkillPoints(50);
}
Related
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Your invoice number is:1234.
Your sale amount is: 10.0.
Your sales tax is: 0.0.-------Problem area
----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.
This will work...
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax = 0.0; // by default this is initialized to zero.
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
public static void main(String args[])
{
setSalePrice(10.0); // sets SalesTax to (100.0 * .05)
displaySalePrice();
}
}
Note that there are some stylistic issues with this class.
"SalesTax" starts with an upper case letter, which is supposed to be reserved for class (and interface) names. The correct spelling is "salesTax".
It lacks a constructor.
Example Constructor:
public Purchase(int invoiceN, double salesP, doubles salesT) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesT;
}
A purchase is a thing that doesn't change once it is made. Its data members are variable (change-able), but they should be invariable (final or constant).
final int invoiceNumber; // These are set in the Constructor.
final double salePrice; // Once they are set, they don't change.
final double salesTax;
The class has setters (which set/change the variables), but it lacks getters (which retrieve the values of the variables without changing them). In general, variables should be declared "private" and "final" whenever possible. So if I wrote this class, I would have written it like this:
Revised example:
public class Purchase
{
private final int invoiceNumber;
private final double salePrice;
private final double salesTax;
// Constructor
public Purchase(int invoiceN, double salesP) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesPrice * .05; // The Constructor can figure this out.
}
public int getInvoiceNumber()
{
return this.invoiceNumber; // "this." is optional
}
public double getSalePrice()
{
return this.salePrice();
}
public double getSalesTax()
{
return this.salesTax;
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + getInvoiceNumber() + ".");
System.out.println("Your sale amount is: " + getSalePrice() + ".");
System.out.println("Your sales tax is: " + getSalesTax() + ".");
}
public static void main(String args[])
{
Purchase shoesPurchase = new Purchase(1234, 10.00);
shoesPurchase.displaySalePrice();
}
}
You are never using the setSalePrice method, hence your SalesTax parameter is never being initialized. You could initialize it like so: double SalesTax = salePrice * 0.05;
You are never calling setSalePrice, so the sales tax never gets set
here's one way to correct this, though really you should probably call setSalePrice before calling displaySalePrice, rather than inside of it
public void displaySalePrice()
{
setSalePrice(salePrice);
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
I have been struggling with this issue for weeks and still cannot get what I need. My CalculatingRocketFlightProfile class holds the constructor with the parameters (totalImpulse, averageImpulse etc...) and the methods which calculates the outputs. My MAIN class has an object which inherits my keyboard entry class. This allows users to input a number. Now, all I need is to use these inputs and calculate a result (using the methods in the CalculatingRocketFlightProfile class) to be displayed. However my object of CalculatingRocketFlightProfile class wont acceppt any parameters or I simply doing something wronng. Please help me out I'm really frustrated.
//CalculatingRocketFlightProfile class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle; //declare variables to store results of calculations
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Setting the parameters
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Mutators - SET
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
public void setTheVehiclesMaximumVelocity(double theVehiclesMaximumVelocity) {
this.theVehiclesMaximumVelocity = theVehiclesMaximumVelocity;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.totalImpulse1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.averageImpulse2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.timeEjectionChargeFires3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.massEmptyVehicle4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.engineMass5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.fuelMass6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass ); //This will give me an error "cant find variables"
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry class (Same for all methods e.g. averageImpulse2, timeEjectionChargeFires3 etc...)
public class kbentry{
double totalImpulse1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
You are not storing the returned information from your kbentry methods. Try this:
System.out.print("\nPlease enter a number for Total Impulse: " );
double totalImpulse = input.totalImpulse1();
System.out.println("You have entered : " + totalImpulse);
Do the same for the other variables, then use those to pass in as arguments for your new object.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask for the diners’ satisfaction level using these ratings: 1 = Totally
// satisfied, 2 = Satisfied,
// 3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber = sc.nextInt();
// Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal = sc.nextInt();
// Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: " +
satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " +
getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber) {
String satisfactionL = "";
if (satisfactionNumber == 1) {
satisfactionL = "Totally-satisfied";
}
if (satisfactionNumber == 2) {
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3) {
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
// This method takes the satisfaction number and returns the percentage of tip
// to be
// calculated based on the number.
// This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber) {
double getPercentage = 0;
if (satisfactionNumber == 1) {
getPercentage = 0.20;
}
if (satisfactionNumber == 2) {
getPercentage = 0.15;
}
if (satisfactionNumber == 3) {
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip =
(subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
Error where it says getPercentage(satisfactionNumber)*subtotal..... says SatisfactionNumber cannot be resolved to a variable
And in the Main method there is a error on
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal)); I believe it is the related to the last error.
In getBillTotal, satisfactionNumber is undefined, it has meaning within the context of the method. In order to use it, you would need to define the variable within the context of the method either as a parameter or as a local variable...
In your main method, You have the same problem with tipPercentage, it's undefined...
Your close. You will need to pass in satisfactionNumber into getBillTotal by adding another parameter. Otherwise it don't know what you are taking about when you say satisfactionNumber. It can't directly see the variables in other functions.
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
Then in your main method call pass it in.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
}
And actually you don't need tipPercentage, in fact it's not even defined in main. Since it can be found by satisfactionNumber you could do this.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(subtotal, satisfactionNumber));
}
...
public static double getBillTotal(double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
OR you could pass in the tipPercentage by calculating it first.
public static void main(String[] args) {
....
double tipPercentage = getPercentage(satisfactionNumber);
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
...
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip = (subtotal + (tipPercentage * subtotal));
return totalWithTip;
}
Any of these last two would be okay.
I just started learning Java and I'm trying to write a program based on an assignment sheet (gave this sheet at bottom of the post). However, I really don't quite understand how to use methods all that well. I've written my methods in the "Customer.java" class, and I'm trying to use them in my "TestCustomer.java" class. However, since I really don't know how to do this, it has turned out horribly. I've searched for information on this, but I just seem to keep making myself more confused. Is there any chance you guys could show me the correct way to use these methods, or at least point me in the right direction? Thank you a ton for any help you can provide.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public Customer (String CustomerName, boolean taxable) {
}
public double calculateTax (double listSaleAmount) {
saleDiscount = listSaleAmount*saleRate;
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable == true) {
taxAmount = netSaleAmount*taxRate;
}
else {
taxAmount = 0.00;
}
saleTotal = listSaleAmount + taxAmount;
return saleTotal;
}
public String printRecord; {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
}
public static double changeTaxAmount (double taxRate) {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
return taxRate;
}
public static double changeSaleRate (double saleRate) {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
return saleRate;
}
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
public static String printSaleRate; {
System.out.println("The Sale Rate is" + saleRate + ".");
}
}
TestCustomer class
import java.math.BigDecimal;
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Double totalOfAllSales = 0.00;
//I have no clue how to actually use the methods I created in the Customer class!
//These are my best guesses, which are obviously wrong
//Any help here would be greatly appreciated!
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
System.out.println("The total of all sales is $" + totalOfAllSales);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
You seem to be confused about the syntax for calling a method. The syntax is as follows:
object.method(arguments)
If there are no arguments it looks like this:
object.method()
Also, you need to use accessor and mutator methods instead of directly setting instance variables like you do here:
customer1.listSaleAmount = 65.00;
You should implement methods like these:
public void setListSaleAmount(double lsa) {
listSaleAmout = lsa;
}
public double getListSaleAmount() {
return listSaleAmount;
}
and make listSaleAmount private.
Problem #2: The syntax for defining the methods. You are using this code to define a method:
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
You should be using this code:
public static String printTaxRate() {
System.out.println("Tax Rate is" + taxRate + "%.");
}
The problem is the weirdly placed semicolon inside the method header.
I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;