Java- Involving objects and multiple classes - java

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

Related

Using return values from methods on ArrayList

Yesterday I posted a question about ArrayList not printing the output from methods, it happened to be just a syntax error. Today, however, I encounter a similar problem with that error fixed. I would appreciate it if someone could tell me what's wrong with this code.
My problem is that the ArrayList prints [0.0, 0.0, 2.75] as opposed to the list of prices I expected.
import java.util.ArrayList;
public class TransitCalculatorTwo {
int numberDays;
int numberRides;
int numberPlanSeven;
int numberPlanThirty;
double totalPriceSeven;
double totalPriceThirty;
double pricePerRideSeven;
double pricePerRideThirty;
double SinglePrice = 2.75;
double sevenDayPrice = 33.0;
double thirtyDayPrice = 127.00;
public int numberPlanSeven(int numberDays) {
int planSeven = (int) Math.ceil (numberDays / 7.0);
return planSeven;
}
public int numberPlanThirty(int numberDays) {
int planThirty = (int) Math.ceil (numberDays / 30.0);
return planThirty;
}
public double totalPriceSeven (int numberPlanSeven, double sevenDayPrice) {
double totalSeven = numberPlanSeven * sevenDayPrice;
return totalSeven;
}
public double totalPriceThirty (int numberPlanThirty, double thirtyDayPrice) {
double totalThirty = numberPlanThirty * thirtyDayPrice;
return totalThirty;
}
public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
double ppRideSeven = totalPriceSeven / numberRides;
return ppRideSeven;
}
public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
double ppRideThirty = totalPriceThirty / numberRides;
return ppRideThirty;
}
public ArrayList<Double> comparePrice() {
ArrayList<Double> prices = new ArrayList<Double>(); for (int i=0; i<1; i++) {
prices.add(pricePerRideSeven);
prices.add(pricePerRideThirty);
prices.add(SinglePrice);
}
return prices;
}
public static void main (String[]args) {
TransitCalculatorTwo customer = new TransitCalculatorTwo();
customer.pricePerRideSeven(66.0, 50);
customer.pricePerRideThirty(127.00, 50);
System.out.println(customer.comparePrice());
}
}
You are not setting variable values in the object you have constructed in main. You are setting values to the local variables and not the objects parameters.Your code must look like this:
public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
this.pricePerRideSeven = totalPriceSeven / numberRides;
return this.pricePerRideSeven;
}
public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
this.pricePerRideThirty = totalPriceThirty / numberRides;
return pricePerRideThirty;
}

Java - Pass on Variables to Method via Constructor

Is it possible to send variables i need in a method via a constructor ?
I have 2 files:
public class Recording {
public int height;
public int diameter;
public int weight;
public Recording (int height, int diameter, int weight) {
this.height = height;
this.diameter = diameter;
this.weight = weight;
}
}
and
public class Leergut {
public static void main(String[] args) {
int height;
int diameter;
int weight;
int code;
int pfand;
while (code != -1) {
Recording r = new Recording(System.in.read(), System.in.read(), System.in.read());
classify(r);
} else {
// to be continued
}
}
public static int classify(Recording r) {
if (height == 250 && diameter = 67 && weight == 365) { code = 0; return code;}
else { code = -1; return code ;}
}
I am looking for a way to pass on height, diameter and weight ( as declared in Recording class) to the "classify" method.
Or do i need to declare the variables inside the method again, in order to make it work ?
PS: For the ones, who tried to help me in my first thread, I decided to make a new post, as it would grant a better overview.
You could create getter and setter methods for the height, diameter and width variables in Recording. Then, call them within your classify method.
Example:
// Methods in Recording.java
public int getWidth() {
return this.width;
}
public int getDiameter()
return this.diameter;
}
public int getHeight() {
return this.height;
}
And in the classify method, just get the values from Recording:
public static int classify(Recording r) {
if(r.getHeight() == 250 && r.getDiameter() == 67 && r.getWidth() == 365) {
// Do whatever
}
}
This is a suggestion
You must initialize the variables, then create 3 methods that return the respective values
public class Recording {
private int height = 0;
private int diameter = 0;
private int weight = 0;
public Recording (int height, int diameter, int weight) {
this.height = height;
this.diameter = diameter;
this.weight = weight;
}
public int getHeight()
{
return height;
}
public int getDiameter()
{
return diameter;
}
public int getWeight()
{
return weight;
}
}
public static int classify(Recording r) {
if (r.getHeight() == 250 && r.getDiameter() == 67 && r.getWeight() == 365) { code = 0; return code;}
else { code = -1; return code ;}
}
you mean this?
public static int classify(Recording r) {
if (r.height == 250 && r.diameter = 67 && r.weight == 365) {
code = 0; return code;
}
else {
code = -1; return code ;
}
Your Recording class and its fields are public, which means that you can access them just by calling their name, dot, and the field you desire to get.
In order to pass variables to a method you can go as this:
public void myMethod(int variable1, boolean variable2) {
//method body
}
You can call it like so:
public static void main(String[] args){
int a = 2;
boolean f = false;
myMethod(a,f);
// If static do:
// ClassThatHasTheStaticMethod.myMethod(a,f);
}
As a side note:
while (code != -1) {
Recording r = new Recording(System.in.read(), System.in.read(), System.in.read());
classify(r);
} else {
// to be continued
}
You cannot put a else statement following a while code block as it will result in a compile error.
Tried a new approach. Declared the variables inside the method again (cant figure out how to call the Setter function with "System.in.read()"
public static int classify(Recording r) {
int height = System.in.read();
int diameter = System.in.read();
int weight = System.in.read();
if (height == 250 && diameter == 67 && weight == 365) {int code = 0; return code;}
else { int code = -1; return code ;}
}
However, now my Object "Recording r" tells me that the variables cannot be resolved anymore
AND
the System.in.read(); for the 3 variables inside the method throw some sort of IOException.

Create a Single Random Value to Share Across Classes Java

Final(?) edit:
Leonardo Pina's solution looks like what I needed. Thank you all for your input! My code is now:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And the implementation in the other class:
public class Damage {
Roll r;
Damage(Roll r) {
this.r = r;
}
public int damageOut() {
int a = r.getR(); //roll value
return a * 2; //test math on r
}
}
Edit:
Thank you for the responses. However, it seems my use of this method was not clear. Apologies! This is what I need:
Call Roll class, get e.g. "12"
OtherClass1 receives "12" from Roll via getter
OtherClass2 also receives "12" from Roll via getter
Call Roll class again, get a new random number, e.g. "48"
OtherClass1 receives "48" from Roll via getter
OtherClass2 also receives "48" from Roll via getter
Using the solutions provided, Roll creates a single random number and never creates a new one again. I need Roll to create random numbers on demand, and then share that random number with other classes. I do not want it to only generate one number and then stop. I hope this makes sense. Thank you for the responses so far!
I have searched for and read the other threads of a similar topic (including this one, which is how I tried to solve my problem), but the methods I have tried have failed. I need to create a single random value and then use that same value across multiple classes.
My random class:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And a class where I call for the static value from the random class:
public class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
When I call the getter from OtherClass, the value is different than the getter from Roll. I would expect them to be the same value.
I call the values for testing like so:
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
Any guidance would be greatly appreciated. Have a good day.
When you create a new instance of OtherClass you also create a new instance of Roll, therefore, the rolls are different.
You need to make sure you are getting the value R from the same object Roll.
This could be achieved by using a singleton pattern for the Roll class, or you could specify the Roll object you want to use to get values, this way you could have several rolls for different purposes. i.e.
Edit:
Answering your edit: to get a new number, you should update the value of r in the Roll class whenever you generate a new value, for example, instead of returning a value, the level() method could update the r variable:
public final class Roll {
private static final Random r1 = new Random();
// We now attribute a value to r uppon construction
private final int r;
public Roll() {
level();
}
// Whenever level() is called the value of r is updated
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
this.r = r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class Game {
public static void main(String[] args) {
// Create the Roll obj
Roll myRoll = new Roll();
// Initialize the other objs with myRoll
Board board = new Board(myRoll);
Player player = new Player(myRoll);
// Do your comparison
int b = board.getRoll();
int p = player.getRoll();
// EDIT: get a new value
myRoll.level();
// Do your comparison once more
b = board.getRoll();
p = player.getRoll();
}
class Board {
Roll r;
Board(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
class Player {
Roll r;
Player(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
}
Probably the simplest way to make it work would be to field r in class Roll as static, so that the Roll class looks like this:
ublic final class Roll {
private static final Random r1 = new Random();
private static final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
Or second approach would be to make Roll class a singleton.
Edit:
Since you have changed the intent of the question, and from what I understand you should look into Observer design pattern. It may be helpful for your case.
As someone said in the comments, you should follow the singleton design pattern, meaning that your variable r should be unique across all Roll class instances. To do this, your code will have to look something like this:
public class RandomTest {
public static void main(String[] args) {
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
}
}
class Roll {
private static Random r1 = new Random();
private static int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
How about sharing the Roll instance?
Roll roll = new Roll();
// roll.roll(); // Unclear how you "refresh" the data
int r = roll.getR();
OtherClass other = new OtherClass(roll);
int o = other.getR();
assert(o == r);
class OtherClass {
private final Roll roll;
public OtherClass(Roll roll) {
this.roll = roll;
}
public int getR() {
return roll.getR();
}
}
Tip: I think a Dice class with a roll() method makes more sense.

ArrayList is not returning the array but the last element [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 7 years ago.
All, I'm having what appears to be simple problem not in loading the array but looping through the list after loading. Seems it always returns the last record loaded regardless. I've tried to limit what was stored in the ArrayList (itemVal=2) to see if that was the only value returned. But it's not. Code below:
import java.util.ArrayList;
public class testNewClass{
// element layout:
// String defTitle
// int seriesVal
// int itemVal
// double x coordinate
// double y coordinate
static String defTitle;
static int seriesVal;
static int itemVal;
static double xCoordinate;
static double yCoordinate;
/*
* Private constructor
*/
private static ArrayList<testNewClass> testList = new ArrayList<testNewClass>();
/*
* Methods
*/
public static void setAll(String title, int series, int item, double x, double y){
testNewClass newTest = new testNewClass();
newTest.defTitle = title;
newTest.seriesVal = series;
newTest.itemVal = item;
newTest.xCoordinate = x;
newTest.yCoordinate = y;
if (item == 2){
testList.add(newTest);
System.out.println("count of testList="+testList.size());
System.out.println("LOADING..series="+series+" item="+item+" x="+x+" y="+y);
}
}
public void setTitle(String title){
this.defTitle = title;
}
public static String returnNext(int Series, int Item){
String rtnVal = null;
System.out.println("testList(size)="+testList.size()+"..Series="+Series+"..Item="+Item);
for (int i=0; i<testList.size(); i++){
int nSeries = testList.get(i).seriesVal;
int nItem = testList.get(i).itemVal;
System.out.println("X="+testList.get(i).xCoordinate);
System.out.println("(i)="+i+" nSeries="+nSeries+" nItem="+nItem);
if (nSeries == Series && nItem == Item){
double lX = testList.get(i).xCoordinate;
double lY = testList.get(i).yCoordinate;
rtnVal = "x=" + lX + " y="+lY;
break;
}
}
return rtnVal;
}
}
I think this code is closer to the mark. Note that the last point is indeed the one it returns, and all the points in the series are independent.
package cruft;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Series encapsulates a List a Points
* Created by Michael
* Creation date 12/20/2015.
* #link https://stackoverflow.com/questions/34387750/arraylist-is-not-returning-the-array-but-the-last-element
*/
public class Series {
private List<Point> points;
public static void main(String[] args) {
Series series = new Series();
double x = 0.0;
double y = 0.0;
double dx = 0.1;
int numPoints = 21;
double minY = -1.0;
double maxY = +1.0;
Random random = (args.length > 0) ? new Random(Long.valueOf(args[0])) : new Random();
for (int i = 0; i < numPoints; ++i) {
series.addPoint(new Point(x, y));
x += dx;
y = minY + (maxY-minY)*random.nextDouble();
}
System.out.println(series);
System.out.println(series.getLastPoint());
}
public Series() {
this(null);
}
public Series(List<Point> points) {
this.points = (points == null) ? new ArrayList<Point>() : new ArrayList<Point>(points);
}
public void addPoint(Point p) {
if (p != null) {
this.points.add(p);
}
}
public Point getPoint(int index) {
return this.points.get(index);
}
public Point getLastPoint() {
return this.getPoint(this.points.size()-1);
}
#Override
public String toString() {
return "Series{" +
"points=" + points +
'}';
}
}
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
#Override
public String toString() {
return "Point{" +
"x=" + String.format("%10.5f", x) +
", y=" + String.format("%10.5f", y) +
'}';
}
}

How do this subclass interact with the main class

I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.
This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}
I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}

Categories