On Geany and my friend's computer this code works. But on my VSCode app it gives the error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method fuelNeeded(int) is undefined for the type Vehicle
The method fuelNeeded(int) is undefined for the type Vehicle
at AddParamVehicle.main(AddParamVehicle.java:18)
I would like to understand why this happens and how to fix it. Thanks.
Edited after I updated to JDK 19, still giving same error.
public class AddParamVehicle {
public static void main (String[] args){
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
double gallons;
int dist = 252;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap =16;
minivan.mpg = 21;
//assign vlaues to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
gallons = minivan.fuelNeeded (dist);
System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel.");
gallons = sportscar.fuelNeeded (dist);
System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel.");
}
}
class Vehicle{
int passengers;
int fuelcap;
int mpg;
// return the range
public int range() {
return fuelcap * mpg;
}
// compute fuel needed for a given distance
public double fuelNeeded (int miles) {
return (double) miles / mpg;
}
}
checking your java version that I think it's old.
Related
This program compiles and runs perfectly if I remove '%%' from the 'toString()' method. However, if I display the percentage symbol, my program crashes right when the 'toString()' method is called (after asking for input). I failed to resolve this issue. Can anybody help me?
I am running this on VSCODE.
// FA2022_Investor_Souza.java
// Data type class
public class FA2022_Investor_Souza {
// Fields
private String name;
private int shareAmount;
private float sharePrice;
private float yearlyDividend;
// No-arg constructor
public FA2022_Investor_Souza()
{
name = "";
shareAmount = 0;
sharePrice = 0f;
yearlyDividend = 0f;
}
// Parameterized constructor
public FA2022_Investor_Souza(String n, int a, float p, float y)
{
name = n;
shareAmount = a;
sharePrice = p;
yearlyDividend = y;
}
// Method to calculate the savings money
public float savingsMoney()
{
float moneyInvested = sharePrice * shareAmount;
float interestAmount = moneyInvested * yearlyDividend * 0.01f;
float moneyReturned = moneyInvested + interestAmount;
return moneyReturned;
}
// Method to display the information
public String toString ()
{
float moneyInvested = sharePrice * shareAmount;
float interestAmount = moneyInvested * yearlyDividend * 0.01f;
return "-------------------------------------------------------\n" +
"FA2022_ShareInvestmentCalculator_Souza.java\n" +
"FALL 2022 semester - MATHEUS SOUZA\n" +
"-------------------------------------------------------\n" +
String.format("%-32.32s%15s\n", "Name of investor: ", name) +
String.format("%-32.32s%15d\n", "Number of shares: ", shareAmount) +
String.format("%-32.32s%15.2f\n", "Price of each share: ", sharePrice) +
String.format("%-32.32s%15.2f%%\n", "Percentage of yearly dividend: ", yearlyDividend) +
String.format("%-32.32s%15.2f\n", "Money Invested: ", moneyInvested) +
String.format("%-32.32s%15.2f\n", "Interest Amount: ", interestAmount) +
"-------------------------------------------------------\n" +
String.format("%-32.32s%15.2f\n", "Total money at the end of year: ", savingsMoney());
}
}
// FA2022_ShareInvestmentCalculator_Souza.java
// Driver class
// Importing Scanner class
import java.util.Scanner;
public class FA2022_ShareInvestmentCalculator_Souza {
public static void main (String [] args)
{
// Creating object for Scanner class
Scanner scanner = new Scanner(System.in);
// Asking for the user's info
System.out.printf("What is your name? ");
String name = scanner.nextLine();
System.out.printf("What is the number of shares? ");
int number = scanner.nextInt();
System.out.printf("What is the price of a share? ");
float price = scanner.nextFloat();
System.out.printf("What is the yearly dividend? ");
float dividend = scanner.nextFloat();
// Creating object for FA2022_Investor_Souza class using parameterized constructor
FA2022_Investor_Souza investor = new FA2022_Investor_Souza(name, number, price, dividend);
// Displaying the result by accessing the method toString()
System.out.printf(investor.toString());
}
}
Relating to this line of your code
String.format("%-32.32s%15.2f%%\n", "Percentage of yearly dividend: ", yearlyDividend)
You want to add another % as a string after the yearlyDividend, correct?
Then you need to tell in the format string that another string is following (%s). Then add the "%%" as string as another parameter, because %'s need to be escaped by another % to be shown as the % sign.
So the working code would look like this:
String.format("%-32.32s%15.2f%s\n", "Percentage of yearly dividend: ", yearlyDividend, "%%")
New to java and I'm confused as to how I can combine these two objects. Sorry if I am not clear / if this has been asked before.
I need to add one.PiggyBank to two.PiggyBank
We are not allowed to change the program used to output the code
public class PiggyBank {
doubles pennies, nickels, dimes, quarters, totalValue, bankTotal;
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
totalValue = pennies + nickels + dimes + quarters;
}
public void addPenny()
{
}
//accessors
public double getP()
{
return pennies;
}
public double getN()
{
return nickels;
}
public double getD()
{
return dimes;
}
public double getQ()
{
return quarters;
}
public double combinePiggy(double bank2)
{
two.
bankTotal = bank1 + bank2;
}
public static void main(String[] args) {
PiggyBank one = new PiggyBank(5, 5, 5, 5);
PiggyBank two = new PiggyBank(2, 3, 4, 1);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
one.combinePiggy(two);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
}
}
You need to create that combinePiggy(PiggyBank) method and then add the values of the parameter to the corresponding values you call this on.
Somewhat abstract and simplified example to get you started (you should do the real thing yourself to have a learning effect):
class Thing {
int x;
int y;
void combine(Thing otherThing) {
x += otherThing.x;
y += otherThing.y;
}
}
There is so much wrong with this. First of all, it does not make sense to have those attributes listed as type double.
For example: pennies = 0.5; this makes no sense, as you cannot have half a penny in a piggy bank. This needs to be adjusted for all accessor and mutator methods.
public class PiggyBank {
int pennies, nickels, dimes, quarters;
double bankTotal;
.
.
.
public int getP()
{
return pennies;
}
public int getN()
{
return nickels;
}
public int getD()
{
return dimes;
}
public int getQ()
{
return quarters;
}
}
Additionally, the combinePiggy method should not have a return type, as you are not returning anything. Furthermore, as the main method suggests, the combinePiggy method should have another piggybank as a parameter. The method should then add the number of each piggy bank together, as well as the total of each bank.
public void combinePiggy(PiggyBank bank2)
{
pennies += bank2.pennies;
nickels += bank2.nickels;
dimes += bank2.dimes;
quarters += bank2.quarters;
bankTotal += bank2.bankTotal;
}
Another thing, judging by the main method, your class needs a toString method. A toString method is exactly what the name implies. It converts an object into a string. (I'll leave it for you to write the appropriate toString to fit your main method)
public String toString(){
return "This piggy bank has " + pennies + " pennies, " + nickels + " nickels, " +
dimes + " dimes, " + quarters + " quarters.";
}
Also, you cannot just add the number of coins in order to get a bank total. Example: You have a penny, a nickel, a dime and a quarter. 0.01+0.05+0.10+0.25=0.41. The way you are doing it, you're bank total would just add up the number of coins.
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
bankTotal = pennies*0.01 + nickels*0.05 + dimes*0.1 + quarters*0.25;
}
I think I've done more than answer your question. I will leave the addPenny as well as the setter methods to you. It seems you are very new to Java. I suggest you watch a few videos and read some documentation about the language before you tackle this assignment. Here is a video that more or less sums up the language.
I am working on eclipse about Java I encountered such problem:
This is the first class
class Vehicle {
int passengers;
int fuelcap;
int mpg;
}
public class VehicleDemo {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
int range;
//assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
//compute the range assuming a full tank of gas
range = minivan.fuelcap * minivan.mpg;
System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range);
}
}
This is the second:
class Vehicle {
int passengers;
int fuelcap;
int mpg;
void range() {
System.out.println("Range is " + fuelcap * mpg);
}
}
public class AddMeth {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
//assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
//assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
System.out.println("Minivan can carry " + minivan.passengers + ". ");
minivan.range(); // display range of minivan
System.out.println("Sportscar can carry " + sportscar.passengers + ". ");
sportscar.range();
}
}
The problem is when I am working in eclipse and deleting the first four line on second class I still have problem with void method. How eclipse is working with multiple classes with methods?
Thank you in advance!
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 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;