Java Error: The constructor is undefined - java

In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
Java Code:
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
public class WeightInApp{
public static void main (String [] args){
WeightIn weight1 = new WeightIn(); //Error happens here.
weight1.setWeight(3.65);
weight2.setHeight(1.7);
}
}
I have a constructor defined.

Add this to your class:
public WeightIn(){
}
Please understand that default no-argument constructor is provided only if no other constructor is written
If you write any constructor, then compiler does not provided default no-arg constructor. You have to specify one.

With your current implementation, you can't do WeightIn weight1 = new WeightIn(); since default constructor is not defined.
So you can add
public WeightIn(){
}
Or you can do this
WeightIn weight1 = new WeightIn(3.65,1.7) // constructor accept two double values

The compiler is encountering a call to a "WeightIn()" no argument constructor, on this line:
WeightIn weight1 = new WeightIn(); //Error happens here.
The compiler is looking for a matching constructor in the class definition, and its not finding it. That's the error. (You do have a constructor defined: "WeightIn(double,double)" but that takes two arguments, and is not match.)
Several ways to fix this.
The easiest is to change the code in your main method to pass two arguments.
WeightIn weight1 = new WeightIn( 3.65, 1.7);
//weight1.setWeight(3.65);
//weight2.setHeight(1.7);
The calls to the setWeight and setHeight methods are redundant, since the members are already assigned values by the constructor method.

You do not have the constructor WeightIn() .Create it or give parameters in main method to constructor.

WeightIn weight1 = new WeightIn();
The default constructor is not defined. Please define it like this:-
public weightIn()
{
}

In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
It's simply because you didn't have the matching constructor for your class:
public class WeightIn {
...
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
you need to add the public WeightIn() {}.
In Java, the default constructor is automatically generated by the compiler if you didn't defined it. So, when you define the following class:
public class WeightIn {
private double weight;
private double height;
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
compiler will generating a matching default constructor for you. So, your class is implicitly having a default constructor like this:
public class WeightIn {
private double weight;
private double height;
// automatically generated by compiler
public WeightIn() {
// do nothing here.
}
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
when you instantiate the class with:
WeightIn weight = new WeightIn();
everything is alright.
But when you're adding a constructor by yourself, the default constructor will not generated by the compiler. So, when you're creating the class with:
public class WeightIn {
...
// this won't automatically generated by compiler
// public WeightIn() {
// nothing to do here.
//}
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
You won't have the default constructor (i.e public WeightIn(){}). And using the following will raise an error because you have no matching constructor:
WeightIn weight = new WeightIn();

First of all, you should know that one .java file can have only one public class.
You are getting error because you have written parameterised constructor and accessing a default constructor. To fix this error write:
WeightIn weight1 = new WeightIn(5.2, 52.2);
instead of
WeightIn weight1 = new WeightIn();

It took me a while but I think I finally figured out a way for this program to work.
I separated the classes into different files and renamed the weight Class to Record just so that it's more obvious instead of everything being named some variation of weight. I also added an Output class to keep the code in the main as clean and minimal as possible.
I hope this is similar to what you were hoping to do.
Original Code: "Constructor"
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn; //needs to be : this.weight = weight
height = heightIn; //needs to be : this.height = height
}
Project: weightInApp
Package: weightInApp
Class: Record.Java
package weightInApp;
class Record
{
private double weight; //declare variables
private double height;
Record (double weight, double height) { //Parameterized Constructor method
this.weight = weight; //this is the correct way
this.height = height;
//if you want to use weightIn and/or heightIn you have to be consistent acrosss
//the whole class. I decided to drop "In" off the variables for brevity.
}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
Project: weightInApp
Package: weightInApp
Class: Output.Java
This class outputs the set values to a table on the console. This can be manually altered to add more data. you could also consider tracking the date of the record and adding that to this output. you would need to add the requisite variables, getters, and setters in the Record Class for that functionality.
package weightInApp;
public class Output {
static void output (Record weightIn1, Record weightIn2)
{
int count = 0;
final Object[][] table = new Object[3][3];
table[0] = new Object[] { "Record", "Weight", "Height"};
table[1] = new Object[] { count +=1, weightIn1.getWeight(), weightIn1.getHeight() };
table[2] = new Object[] { count+=1, weightIn2.getWeight(), weightIn2.getHeight() };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s\n", row);
}
}
}
Project: weightInApp
Package: weightInApp
Class: Main.Java
package weightInApp;
import weightInApp.Record; //imports methods and variables from the other classes
import weightInApp.Output;
public class Main {
public static void main (String [] args){
Record weightIn1 = new Record(0,0);
//previous line of code creates a new Record object named weightIn1
//previous line of code also sets both the values of weight and height to 0.
weightIn1.setWeight(3.65); //sets weight for weightIn1
weightIn1.setHeight(1.70);//sets Height for WeightIn1
Record weightIn2 = new Record(0, 0);
weightIn2.setWeight(3.00);
weightIn2.setHeight(1.75);
//previous 3 lines are the same as above for weightIn1
//except this is for a second object named weightIn2
Output.output(weightIn1, weightIn2); //calls runs passes values to output method
}
}
Sample Output
output sample from console

Related

Instantiate array of objects with a variable

I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:
public class Bank {
private String name;
private int maxbankaccount;
private int activebankaccount;
private String radice = "IT8634";
private Conto[] bankaccount = new Conto[maxbankaccount];
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
}
}
I wrote a tester class to test :
public class TestBank {
public static void main (String[] args) {
Bank b1 = new Bank("Fidelity", 10);
b1.addconto("PROVA");
}
}
Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?
private Conto[] bankaccount = new Conto[maxbankaccount];
This initialization takes place before the rest of the constructor runs.
Move it into the constructor:
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
this.bankaccount = new Conto[maxbankaccount];
}
You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.
Move it into the constructor and initialize it.
public Bank(String name, int maxbankaccount) {
/* ... */
this.bankaccount = new Conto[maxbankaccount];
}
Further more than the issues that are in the other answers, this
private int activebankaccount;
does not initialize the variable activebankaccount
So in:
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
you are using an uninitialized vale as index of the array bankaccount

Passing Value In Java

I was given a task to create a java program that use this 3 classes. Main class, Menu class and Coffee Class. Now i need to pass value from menu class to coffee class. But the problem is i dont exactly know how to do it since im still new with java.
CoffType pass the value to CoffeeName.
NumBag pass the value to NumberOfBag.
This is menu class(programmer defined class 1)
import java.util.*;
public class Menu {
Scanner scan = new Scanner(System.in);
public String coffType;
public int numBag;
public void setCoffType() {
System.out.println("\t\tChoose Your Coffee");
System.out.println("\n[1] Arabica\tRM12.50 per bag");
System.out.println("\n[2] Robusta\tRM15.00 per bag");
coffType = scan.nextLine();
}
public void setNumBag() {
System.out.println("Enter amount you wish to buy");
numBag = scan.nextInt();
}
}
Coffee Class(programmer defined class 2)
public class Coffee{
private String coffeeName;
private double coffeePrice;
private double amountPay;
private int numberOfBag;
private double discount;
public Coffee() { // constructor
coffeeName = "unknown";
coffeePrice = 0.00;
amountPay = 0.00;
numberOfBag = 0;
discount = 0.00;
}
public double getCoffeePrice() {
if(coffeeName.equalsIgnoreCase("arabica")) {
coffeePrice = 12.50 * numberOfBag;
}
else if(coffeeName.equalsIgnoreCase("robusta")) {
coffeePrice = 15.00 * numberOfBag;
}
System.out.println("Price RM: " +coffeePrice);
return coffeePrice;
}
public double getDiscount() {
if(numberOfBag>0 && numberOfBag<=50) {
discount = coffeePrice*0;
}
if(numberOfBag>50 && numberOfBag<=100) {
discount = coffeePrice*0.10;
}
if(numberOfBag>100 && numberOfBag<=150) {
discount = coffeePrice*0.15;
}
if(numberOfBag>150 && numberOfBag<=200) {
discount = coffeePrice*0.20;
}
if(numberOfBag>200) {
discount = coffeePrice*0.25;
}
System.out.println("Discount RM: " +discount);
return discount;
}
public double getAmountPay() {
amountPay = coffeePrice - discount;
System.out.println("\nTotal Need To Pay RM: " +amountPay);
return amountPay;
}
}
I want to pass coffType to coffeeName and numbag to numberOfBag. How can i change these values?
In CoffeClass create a constructor that receives the parameter that you want to set:
public Coffee(String coffeeName, double amountPay, int numberOfBag) {
this.coffeeName = coffeeName;
this.amountPay = amountPay;
this.numberOfBag = numberOfBag;
}
In MenuClass you will instantiate the object Coffe with the selected values by the user:
Coffe coffeOne = new Coffe(coffeName, amoutPay, numBag);
In the same class use the object to get the discount:
double discountCoffeOne = coffeOne.getDiscount();
You're done.
You use the CoffeClas as a model to an object with the values that you want. That way you can have a lot of different coffe just instantiating another Coffe with another name and using it.
When needed you should use getters and setters to change the attributes of an object, when needed means you should not create them when the values are not supposed to change or the other classes should not have permission to change these attributes.
public setCoffeeName(String coffeeName){
this.coffeeName = coffeName
};
public getCoffeeName(){
return coffeName;
}
;)
Oh, and just like azro said:
"Please follow conventions, and start naming attributs/variables with lowercase"
Here, inorder to pass the value of CoffType to CoffeeName and NumBag to NumberOfBag we can either use a parameterized constructor or setters. Both ways we can pass the value from Menu class to Coffee class.
Using parameterized constructor
create parameterized constructor in the Coffee class and instantiate the Coffee class from the Menu class.
Setter
create 2 setters to set each of NumberOfBag and CoffeName in the Coffee class and set the value by instatiating Coffee class and setting the value to both.

Do i need to add objects dynamically in this case?

So i've been asked to create a simple solar system simulator for my coursework. Our lecturer has set out very specific guidelines in terms of the structure of constructors and methods of our classes.
I've been thinking about this for a couple of hours and don't understand how i can make this work without dynamic object allocation. I want to add planets onto the Planet[] array so they can be indexed, but i don't know how i should create the objects considering a requirement is that you can add planets to the system until the user types 'DONE'.
The Planet class is not one of the requirements but he recommended we use a class that can store the variables for a single planet and do calculations on it. Whereas the data should be stored in the main SolarSystem class. We also need to use a FantasySolarSystem class to read data from the user and deal with output.
import java.util.*;
public class SolarSystem{
public static final int PLANET_MAX = 10;
public static void main(String[] args){
String systemName;
Planet[] planetArray = new Planet[PLANET_MAX]; //const for array size seemed easier than dynamically allocating memory
SolarSystem mySystem = new SolarSystem("Boris");
// below is testing the addplanet function
addPlanet("Jimmy", 10, 100);
System.out.print(Planet[0].planetName);
}
public SolarSystem(String name){
systemName = name;
}
public static void addPlanet(String planetName, double planetMass, double planetDistance){
Planet newPlanet = new Planet(planetName, planetMass, planetDistance);
// all i want to do here is add planets on to the array
Planet[0] = newPlanet;
}
}
Just for reference here is the Planet class:
public class Planet{
private String planetName;
private double planetMass;
private double planetDistance;
private double planetPeriod;
public Planet(String planetName, double planetMass, double planetDistance){
this.planetName = planetName;
this.planetMass = planetMass;
this.planetDistance = planetDistance;
}
//sets the period for the current object
public static calculatePeriod(double planetDistance){
double period = Math.sqrt(planetDistance*planetDistance*planetDistance);
setPlanetPeriod(period);
}
//accessors
public String getPlanetName(){
return planetName;
}
public double getPlanetMass(){
return planetMass;
}
public double getPlanetDistance(){
return planetDistance;
}
public double getPlanetPeriod(){
return planetPeriod;
}
//mutators
public void setPlanetName(String planetName){
this.planetName = planetName;
}
public void setPlanetMass(double planetMass){
this.planetMass = planetMass;
}
public void setPlanetDistance(double planetDistance){
this.planetDistance = planetDistance;
}
public void setPlanetPeriod(double planetPeriod){
this.planetPeriod = planetPeriod;
}
}
Any assistance would be much appreciated.
edit: I would just write it and test it but im getting errors saying, cannot find symbol in places referring to the object array
edit2: Fixed the accessing non-static methods from static methods issue, but still having problems with adding objects to arrays (still have 3 more cannot find symbol errors, with systemName=name; and both times i use Planet[0])

How can I share instantiated objects between methods?

I have:
public class HFSim extends ApplicationTemplate
{
private static class AppFrame extends ApplicationTemplate.AppFrame
{
void setBuoy()
{
//code
Position buoypos=Position.fromDegrees(buoylat, buoylon);
}
void setVehicle()
{
//code
Position vehiclepos=Position.fromDegrees(lat, lon, elev);
}
double findDistance()
{
//find distance between marker (vehicle) and a buoy
Earth earth= new Earth();
double radius = earth.getEquatorialRadius();
double distancebetween=LatLon.ellipsoidalDistance(buoypos, vehiclepos, radius, 6356752.3);
return distancebetween;
}
How can I use the objects buoypos and vehiclepos in the setBuoy and setVehicle methods in the findDistance() method?
You have two clearcut options here:
Make buoypos and vehiclepos instance variables, or..
Provide more descriptive names for setVehicle() and give it a Position return type.
Option 1 would look like this:
...classname...
{
private Position vehiclePosition;
private Position bouyPosition;
public void setVehiclePosition()
{
this.vehiclePosition = ....
}
}
Option 2 would look like this:
...classname...
{
public Position createVehiclePosition()
{
vehiclePosition = ....
return vehiclePosition.
}
}
Finally, you would use them as either:
...classname...
{
public double findDistance()
{
...this.vehiclePosition...
or
Position vehiclePos = this.createVehiclePosition();
}
}
The option you choose is highly dependent on how the class is supposed to behave.
Use variables with the class scope. This essentially means
///outside of a method but within the class you'll want to set:
private this.bouypos = new Position;
private this vehiclepos = new Position;
//method1 {
Position this.buoypos=Position.fromDegrees(buoylat, buoylon);
//method2 {
Position this.vehiclepos=Position.fromDegrees(lat, lon, elev);
//method3 calls things set in method1 & 2
findDistance(){
//code
double distancebetween=LatLon.ellipsoidalDistance(this.buoypos, this.vehiclepos, radius, 6356752.3);
}
Make the findDistance method take two Positions as parameters
double findDistance(Position buoypos, Position vehiclepos){
}

Having issues creating an application that instantiates an object of each type and displays the details

First I'm new and don't know if this is against the rules but I'm looking for a little help on my homework. I don't want a full answer, just a step in the right direction. The problem is as follows:
Mick’s Wicks makes candles in various sizes. Create a class for the business named Candle that contains data fields for color, height, and price. Create get methods for all three fields. Create set methods for color and height, but not for price. Instead, when height is set, determine the price as $2 per inch. Create a child class named ScentedCandle that contains an additional data field named scent and methods to get and set it. In the child class, override the parent’s setHeight() method to set the price of a ScentedCandle object at $3 per inch. Write an application that instantiates an object of each type and displays the details. Save the files as Candle.java, ScentedCandle.java, and DemoCandles.java.
Now I believe I have done the classes correctly but the issue I'm having is the "Write an application that instantiates an object of each type and displays the details." I just dont get it. Here's my code:
public class Candle {
public static int color; //Declaring Variables
public static int height;
public static int price;
Candle(int startColor, int startHeight, int startPrice) { //Constructor
color = startColor;
height = startHeight;
price = startPrice;
}
public static int getColor() //Public methods
{
return color;
}
public void setColor(int color)
{
Candle.color = color;
}
public static int getHeight()
{
return height;
}
public void setHeight(int height)
{
Candle.height = height;
}
public static int getPrice()
{
return price;
}
public void setPrice(int price)
{
Candle.price = 2 * height;
}
}
public class ScentedCandle extends Candle { //Creating subclass to superclass Candle
public static int scent; //Delcare Variable
public ScentedCandle(int startScent,int startColor, int startHeight,int startPrice) { //Constructor
super(startColor, startHeight, startPrice); //Calling from superclass Candle
scent = startScent;
}
public static int getScent() //Public methods
{
return scent;
}
public void setScent(int scent)
{
ScentedCandle.scent = scent;
}
public static int getPrice()
{
return price;
}
#Override
public void setPrice(int price)
{
Candle.price = 3 * height;
}
}
public class DemoCandles { //Here is where I'm lost and have no clue
public static void main(String[] args) {
Candle getColor; //Declaring Variables
Candle getHeight;
Candle getPrice;
ScentedCandle getScent;
getColor = new Candle();
getHeight = new Candle();
getPrice = new Candle();
getScent = new ScentedCandle();
}
}
First of all you need to declare price as a product of height and 2.
"Write an application that instantiates an object
of each type and displays the details."
This basically mean Create a class with a main method in order to run your program.
In that main method, you need to instantiate your Candle class.
Instantiate means to create an object instance of your Candle class.
Something like this:
Object object = new Object(someInt, someInt, someInt); // or which ever constructor you decide to you
In order to get the properties of the object, use your get methods. If the property(data field) does not have a get method, get the property with something like this Object.property
And do like RC said, read up on static. You're not using it right

Categories