Completing a class definition - java

Suppose that you are given the following PetDriver class, which includes a main method:
public class PetDriver{
public static void main(String[] args){
int weight = 40;
Pet doggie = new Pet("Rover", weight);
System.out.println("my pet's name is " + doggie.getName());
System.out.println("my pet's weight is " + doggie.getWeight());
}
}
Executing main produces the following output:
my pet's name is Rover
my pet's weight is 40
My code is as follows but It is returning null.
public class pet {
public String name;
public int weight = 40;
public Pet (String y, int x){
y = name;
x = weight;
}
public String getName(){
return name;
}
public int getWeight(){
return weight;
}
}
Thanks!

In your constructor, you should do it the other way around:
public Pet (String y, int x){
name = y; // instead of y = name
weight = x; // instead of x = weight
}
What you did was assigning the member value to the parameters of the constructor, instead of the other way around. Therefore the member value nameitself was never written, and therefore it was null.

Your constructor does not assign the value to the properties. Change them to the following.
public Pet (String y, int x){
name = y;
weight = x;
}

Related

Java create a unique ID for each instantiated object using instance methods instead of class/static methods

Quite new to this so I hope I have the terminology in the title right.
I am trying to figure out how to create an instance method that will do the following:
--An ID number is returned.
--As each object is created from the class constructor(instantiated?), a unique integer ID number is assigned to it. The first ID number is 1, and as new objects are instantiated, successive numbers will be assigned.
I am able to find examples of class/static methods that do the above however I am unable to figure out how to do this with an instance method. My attempt is below:
class Coordinates
{
private int iD = 0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
iD++;
}
public getiD()
{
return iD;
}
}
My main method is as follows:
public class Machine
{
public static void main(String[] args)
{
Coordinates c1 = new Coordiantes();
Coordinates c2 = new Coordiantes();
Coordinates c3 = new Coordiantes();
System.out.println("ID: " + c1.getID());
System.out.println("ID: " + c2.getID());
System.out.println("ID: " + c3.getID());
}
}
Please note I have not included my entire code for the sake of simplicity and easiness to follow. I hope I have added enough.
I also don't want to use java.util.UUID.
The problem right now is that your 'id' is an instance variable, meaning it belong to the objects you create.
Think of it that every time you create an object a new and fresh copy of your instance variable is made.
So every time you create an object the id is first set to 0, then post incremented once (thus all objects have an id=0).
If you want to create a variable that, say, automatically counts all objects you have created in a class or has the id, you need to make a class variable.
These variable belong to all the objects you create from a class and the keyword used for that is 'static'.
Note: I have used a static variable BUT not a static method. If you don't want to use static at all, it is a different question
class Coordinates
{
private static int count = 0;
private int id=0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
id=count++;
}
public getiD()
{
return iD;
}
}
A simple change of keyword will make your program correct. You dont have to do too much complicated stuff.
It is difficult to grasp the concept of class and objects, static and instance variables at first. Let me know if you'd like more explanation :)
In the context of your current code, the simplest thing to to do is as below:
import java.util.concurrent.atomic.AtomicInteger;
public class Coordinates {
//static id generator shared among all instances of Coordinates
private static final AtomicInteger idGenerator = new AtomicInteger(1000);
private final Integer id;
public Coordinates() {
//assign unique id to an instance variable
id = idGenerator.getAndIncrement();
}
public int getId() {
//return instance variable
return id;
}
}
Test
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10; ++ i){
System.out.println(new CoordinatePoint().getId());
}
}
}
Output
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
Maintaining an ID sequence is a separate responsibility from the rest of what your object does, and doesn't belong to any one instance of the Coordinates class, so it belongs in a different object. Make a separate object to maintain the sequence and hand out numbers, something like
public class MySequence {
private AtomicLong currentValue = new AtomicLong(0L);
public long getNextValue() {
return currentValue.getAndIncrement();
}
}
then use that sequence to initialize your objects:
new CoordinatePair(mySequence.getNextValue(), x, y);
By the way keeping user input separate from the model makes things simpler, you may want to instantiate your Coordinates class in cases where the input doesn't come from the user. Console input doesn't go in a constructor. You might have a Coordinate class like
public CoordinatePoint {
private long id;
private float x;
private float y;
public CoordinatePoint(long id, float x, float y) {
this.id = id;
this.x = x;
this.y = y;
}
public String toString() {
return "id=" + id + ", (" + x + ", " + y + ")";
}
}
and a main method like
public class Example {
public static void main(String ... args) {
MySequence seq = new MySequence();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
float xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
float yCoordinate = keyboard.nextDouble();
CoordinatePoint c1 = new CoordinatePoint(seq.getNextValue(), xCoordinate, yCoordinate);
System.out.println(c1.toString());
}
}
You can either make that ID static, or you could just make a Parent class called "Coordinate" (with that ID again being static) with "Point" children, and increment the ID in the constructor of each "Point" object.
Static would seem like the way to go.

Java- Involving objects and multiple classes

My problem is that for the getTime(); command, you need all of the speed, handling, xcord, ycord, and the terrainDifficultry variables to have an answer, yet I can only call getTime(); from the mb1 class. Basically, I keep getting 0.0 when i get to System.out getTime() and I don't know how to fix it.
import java.util.Scanner;
public class Main_MoonRace {
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter the speed of the moonbuggy as an integer.");
int s = keyboard.nextInt();
System.out.println("Enter the handling of the moonbuggy (between 0-0.9)");
double h = keyboard.nextDouble();
moonbuggy mb1 = new moonbuggy(s,h);
System.out.println("Enter the x-coordinate of where the moonbuggy will be headed to as an integer.");
int xcord = keyboard.nextInt();
System.out.println("Enter the y-coordinate of where the moonbuggy will be headed to as an integer.");
int ycord = keyboard.nextInt();
System.out.println("Enter the difficulty of the terrain that the moonbuggy will be experiencing (integer from 1-10).");
int terrainDifficulty = keyboard.nextInt();
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime());
}
}
moonbuggy.java
public class moonbuggy {
private int speed = 1;
private double handling = 0;
moonbuggy(){
return;
}
moonbuggy(int s, double h){
speed = s;
handling = h;
return;
}
public void setSpeed (int s){
speed = s;
}
public void setHandling (double h){
handling = h;
}
public int getSpeed(){
return speed;
}
public double getHandling(){
return handling;
}
MoonLocation obj1 = new MoonLocation();
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
}
MoonLocation.java
public class MoonLocation {
private int x = 0;
private int y = 0;
private int terrain = 1;
MoonLocation(){
return;
}
MoonLocation(int xcord, int ycord, int terrainDifficulty){
x= xcord;
y = ycord;
terrain = terrainDifficulty;
return;
}
public void setX (int xcord){
x = xcord;
}
public void setY (int ycord){
y = ycord;
}
public void setTerrain (int terrainDifficulty){
terrain = terrainDifficulty;
}
public int getX () {
return x;
}
public int getY () {
return y;
}
public int getTerrain () {
return terrain;
}
public double getdistance () {
double distance = Math.sqrt((Math.pow(x,2))+(Math.pow(y,2)));
return distance;
}
}
Have a look at this part of code in your moonbuggy class (note that by convention a class should always start with uppercase in java).
MoonLocation obj1 = new MoonLocation();
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
You instanciate a MoonLocation without any parameters, then you access it in your getTime method. This explain why you always get 0.0 as result when calling getTime.
Now modify your getTime method to
public double getTime(MoonLocation location){
return (((location.getdistance())/(getSpeed()))*(location.getTerrain())*(1-(getHandling())));
}
Notice that I removed the time variable as it is completly useless there.
And change in your main
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime());
To
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime(mL1));
Also, please remove the unused MoonLocation obj1 = new MoonLocation() in your moonbuggy class.
The Problem lies with your code. In the first place, you are creating an object of MoonLocation in Main_MoonRace class under main() method as :
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
Here, an object of MoonLocation is created and initialized with xcord, ycord, and terrainDifficulty values.
Now, in your MoonBuggy class, again you are creating an object of MoonLocation as :
MoonLocation obj1 = new MoonLocation();
Here, only an empty object of MoonLocation class is created.
Now, when you call :
obj1.getDistance(); It will return 0 only.
Below is the corrected code for MoonBuggy class.
public class Moonbuggy {
private int speed = 1;
private double handling = 0;
Moonbuggy(){}
Moonbuggy(int s, double h){
speed = s;
handling = h;
}
public void setSpeed (int s){
speed = s;
}
public void setHandling (double h){
handling = h;
}
public int getSpeed(){
return speed;
}
public double getHandling(){
return handling;
}
private MoonLocation obj1;
public MoonLocation getObj1() {
return obj1;
}
public void setObj1(MoonLocation obj1) {
this.obj1 = obj1;
}
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
}
and an addtion in the main() method :
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
mb1.setObj1(mL1); // set the MoonLocation object
System.out.println(mb1.getTime());
Now , you will get the proper output

Java Code Questions

I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}
Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.

Possible fix for getting NaN in java

I have a method in the Candy Class named pricePerHundredGrams and what it is supposed to do is multiply the variable price times 100.00 and divide that answer by the variable weightGrams, and finally return that result to the variable wammy. When the variable wammy is called for in the very 2nd last statement of this code, it is supposed to pass the answer to return result. And ultimately c1 and c2 should display that result as well...but I get NaN for "per hundred grams". What is wrong with my code?
public class whatever
{ public static void main (String[] args)
{
processCandies();
System.out.println("end of processing");
}
public static void processCandies()
{
Candy c1 = new Candy("Hershey", 145, 4.35, 233);
Candy c2 = new Candy("Milky Way", 390, 2.66, 126);
System.out.println(c1);
System.out.println(c2);
}
}
class Candy
{
private String name;
private int calories;
private double price;
private double weightGrams;
double wammy = pricePerHundredGrams(price, weightGrams);
/**
Constructor
#param name
#param calories
#param price
#param gram
*/
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
}
public String getName()
{
return name;
}
public int getCalories()
{
return calories;
}
public double getPrice()
{
return price;
}
public double getWeightGrams()
{
return weightGrams;
}
public double pricePerHundredGrams(double price, double weightGrams)
{
return (price * 100.00) / weightGrams;
}
public String toString()
{
String result;
result = name + "\n" + calories + " calories\n" + weightGrams + " grams\n" + wammy + " per hundred grams\n";
return result;
}
}
You are initializing wammy with the result of pricePerHundredGrams, but price and weightGrams haven't been initialized yet, so they're both 0. For double arithmetic, 0 divided by 0 is NaN (it's indeterminate in math).
Initialize wammy after price and weightGrams have valid values in your constructor:
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
// Initialize wammy here.
wammy = pricePerHundredGrams(price, weightGrams);
}
Additionally, since they are already instance variables, you don't need to pass price and weightGrams as parameters to pricePerHundredGrams.

creating a method that calculates averages from an array (java)

Write a static method named calculateAverageWeight, to be added to the Bowl class, which is passed an array of Bowl objects, and returns the average weight of the Bowls in the array.
this is the Bowl class:
public class Bowl {
private double weight;
private boolean empty;
private String origin; // country of manufacture
public Bowl(double w, boolean e, String origin) {
weight = w;
empty = e;
this.origin = origin;
}
public double getWeight() {
return weight;
}
public boolean getEmpty() {
return empty;
}
public String getOrigin() {
return origin;
}
public void setEmpty(boolean emptyStatus) {
empty = emptyStatus;
}
public String toString() {
return ("from " + origin + " weight: " + weight);
}
The following code worked:
public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}
but I don't understand why my most recent code didn't as they seem to run almost identically to me?:
public static double calculateAverageWeight(Bowl[] bowls){
double sum=0;
double k=bowls.length;
for(int j=0; j<bowls.length; j++){
sum=sum+bowls[j].getWeight();}
double average=sum/k;
return average;}
The code for the calculateAverageWeight is OK, but you're missing a "}" at the end of the Bowl class.
Also, your calculateAverageWeight method must be inside another class, so you may be missing something there too. May you post your code ?
public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}

Categories