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.
Related
We all know how to correctly check for fractional numbers in tests (using TOLERANCE):
class OxygenTankTest {
static final double TOLERANCE = 0.001;
#Test
void testFilling() {
OxygenTank tank = OxygenTank.withCapacity(100);
tank.fill(5.8);
tank.fill(5.6);
Assertions.assertEquals(0.114, tank.getStatus(), TOLERANCE);
}
}
But my question is how to check if we need to check not the individual values - but whole objects.
For example:
Need to test Summer - which performs the summation of fields
public class Summer {
public void setSum(Item itemTo, Item itemFrom) {
itemTo.setDiameter(itemTo.getDiameter() + itemFrom.getDiameter());
itemTo.setLength(itemTo.getLength() + itemFrom.getLength());
}
}
public class Item {
private Double diameter;
private Double length;
public Item(Double diameter, Double length) {
this.diameter = diameter;
this.length = length;
}
public Double getDiameter() {
return diameter;
}
public void setDiameter(Double diameter) {
this.diameter = diameter;
}
public Double getLength() {
return length;
}
public void setLength(Double length) {
this.length = length;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
if (diameter != null ? !diameter.equals(item.diameter) : item.diameter != null) return false;
return length != null ? length.equals(item.length) : item.length == null;
}
#Override
public int hashCode() {
int result = diameter != null ? diameter.hashCode() : 0;
result = 31 * result + (length != null ? length.hashCode() : 0);
return result;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Item{");
sb.append("diameter=").append(diameter);
sb.append(", length=").append(length);
sb.append('}');
return sb.toString();
}
}
How i try to write a test:
public class SummerTest {
#Test
public void setSum() {
Summer summer = new Summer();
Item itemFrom = new Item(2.321, 1.111);
Item itemTo = new Item(0.999, 0.999);
summer.setSum(itemFrom, itemTo);
// expected
Item expectedItem = new Item(3.32, 2.11);
assertThat(itemFrom, equalTo(expectedItem));
}
}
But it does not work!
java.lang.AssertionError:
Expected: <Item{diameter=3.32, length=2.11}>
but: was <Item{diameter=3.3200000000000003, length=2.11}>
Expected :<Item{diameter=3.32, length=2.11}>
Actual :<Item{diameter=3.3200000000000003, length=2.11}>
<Click to see difference>
How to properly check for compliance?
You overwrote the equals method that checks for exact equality. If you have objects that contain floating point values (float, double) that are considered in your equals implementation, you will want to not compare the object itself, but the values within the object:
assertEquals(expected.getDiameter(), itemFrom.getDiameter(), TOLERANCE);
assertEquals(expected.getLength(), itemFrom.getLength(), TOLERANCE);
Or if you want to get fancy you can create your own Matcher that goes into the assertThat.
Consider changing the set up of the test to allow for exact comparisons via Item::equals:
private static final double ITEM_FROM_DIAMETER = 2.321;
private static final double ITEM_FROM_LENGTH = 1.111;
private static final double ITEM_TO_DIAMETER = 0.999;
private static final double ITEM_TO_LENGTH = 0.999;
Item itemFrom = new Item(ITEM_FROM_DIAMETER, ITEM_FROM_LENGTH);
Item itemTo = new Item(ITEM_TO_DIAMETER, ITEM_TO_LENGTH);
Item expectedItem = new Item(ITEM_FROM_DIAMETER + ITEM_TO_DIAMETER, ITEM_FROM_LENGTH + ITEM_TO_LENGTH);
Also, since Item is mutable, it would be a good idea to assert itemFrom was not changed.
package polygongeneric;
import java.util.ArrayList;
public class Polygon {
private ArrayList <Point2d> p = null;
private int points = 0;
public Polygon() { }
public Polygon(int numPoints) {
p = new ArrayList<>();
}
public boolean addPoint(Point2d point) {
p.add(points, point);
points++;
return true;
}
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
p.add(points, a);
return true;
}
#Override
public String toString() {
String s = "";
for (int i=0; i<points; i++)
s += p.get(i).toString() + "\n";
return s;
}
}
I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.
This is what my code outputs
(0.1,0.9)
(0.5,0.5)
(0.2,0.5)
This is what it's supposed to output
(0.1,0.9)
(0.3,0.7)
(0.5,0.5)
(0.4,0.8)
(0.2,0.5)
Do you guys have any idea. What I'm doing wrong?
This is my Point2d class
package polygongeneric;
public class Point2d {
private double x = 0, y = 0;
public Point2d() { }
public Point2d(double x, double y) {
setX(x);
setY(y);
}
public void setX(double initX) {
if (initX >= 0 && initX <= 1)
x = initX;
}
public void setY(double y) {
if (y >= 0 && y <= 1)
this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public String toString() {
return "(" + x + "," + y + ")";
}
}
This is my main method
package polygongeneric;
public class PolygonGeneric {
public static void main(String[] args) {
Polygon p = new Polygon(5);
p.addPoint(new Point2d(.1, .9));
p.addPoint(.3, .7);
p.addPoint(new Point2d(.5, .5));
p.addPoint(.4, .8);
p.addPoint(new Point2d(.2, .5));
System.out.println(p);
}
}
You are not incrementing the position in your addPoint(double x, double y), so basically, you are replacing the existing point with a new point, so you are missing few point values and you need to correct the correct the code as shown below:
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x, y);
p.add(points, a);
points++;
return true;
}
Because you are simply adding the point at the end of the list, I suggest you can directly use arraylist.add(point); so that you will not get into these increment/other issues.
Also, you can change your constructor of Polygon class (which accepts int) as follows because you are not using the numPoints variable or else use an array with numPoints as the size instead of ArrayList.
public Polygon() {
p = new ArrayList<>();
}
You did not increment points in the addPoint(double x, double y) function.
Why not reuse the same method? and call the overloaded function
public boolean addPoint(Point2d point); instead of writing the same logic again and again.
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
return addPoint(a);
}
I've made a main method in one class and a lot of other small methods in another class. When I call on them in my main method using their location and making sure that they would outprint if I called on them, they still don't outprint. Only the print two methods show any output. I'm not sure how to go about fixing it so I haven't tried many things yet. Could you look at my code and check why they aren't working?
Update: I've managed to get all the line in the main method except for 28 working with the help I received. Now all that's left is that one output. I've changed the code so it works a bit better and will shut down if it doesn't output, but the output is still missing.package rational;
My Main Method
package rational;
/**
*
* #author Dominique
*/
public class Rational {
public static String number() {
rational1 number= new rational1(27, 3);
String r3= number.printRational(number);
return r3;
}
public static void main(String[] args) {
rational1 number= new rational1(27,3);
System.out.println(number());
String r3=number();
System.out.println(rational1.toDouble(27,3 ));
rational1.add(number);
rational1.invert(r3, number);
rational1.negate(r3, number);
rational1.toDouble(27, 3);
}
}
My Other Method Class
package rational;
/**
*
* #author Dominique
*/
public class rational1 {
public int top;
public int bottom;
public rational1 () {
this.top = 0;
this.bottom = 0;
}
public rational1(int top, int bottom){
this.top=top;
this.bottom=bottom;
}
public String printRational(rational1 r1){
String r3=("Your fraction is "+String.format(r1.top+" / "+r1.bottom));
return r3;
}
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('s');
if (index != -1) {
System.out.print(r2.substring(0, index+1));//works
System.out.println(" "+r1.bottom + "/" + r1.top);
index++;
}
else {
System.exit(0);
}
}
public static void negate(String r2, rational1 r1){
int index = r2.indexOf('-');
if (index != -1) {
String stringValueOf = String.valueOf(r1.top);
System.out.println(r2.substring(0, 17));//works
System.out.println(r1.bottom+"/"+stringValueOf.substring(1));
index++;
}
}
public static double toDouble(int one, int two){
int three= one/two;
return three;
}
public static double gcd( double a, double b)
{
double r = a % b;
if (r != 0)
{
return gcd(b, r );
}
else
{
return b;
}
}
public static double reduce(double t, double b){
double numberone=gcd(t, b);
double pick=numberone*(b/t);
return pick;
}
public static double add(rational1 r1){
double pickone=(r1.top);
double choice= pickone+pickone;
double choice2=reduce(choice, r1.bottom);
return choice2;
}
}
So the problem is in invert method:
public static void invert(String r2, rational1 r1){
int index = 0;
while (index < 1) {
if (r2.charAt(index) == '/') {
System.out.print(r2.substring(0, 17));
System.out.print(r1.bottom+"/"+r1.top);
index++;
}else{
System.exit(0);
}
`}
}
This method immediate checks the character at r2.charAt(index) == '/'), but this is never the case. Because the character at index = 0 is 'Y' from the printRational method. Because that's not the case then System.exit(0) gets called which immediately ends the program without running the rest of the program.
I believe that this code will work.
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('/');
if (index != -1) {
index++;
}
else {
System.out.print(r2.substring(0, index));//works
System.out.print(r1.bottom + "/" + r1.top);
}
}
The print method does not necessarily flush the buffer to the screen. Try replacing the print method with the println method.
Once this is in rational package., try to change the system.out.print to system.out.println .Basically all your codes are okay. Try look at this link.
Click [here] (http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html)!
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
I need to create a method largerThan(See below) which takes a Rectangle object as an argument and returns true if the invoking object has a greater area than the object which is the argument and will return false otherwise. I've done this before but simply can't recall how to complete the code in this part of the method. Any help will be truly appreciated! NOTE: Professor doesn't want us to use the "this" operator! :-(
public class Rectangle
{
private double length;
private double width;
public Rectangle()
{
length = 0;
width = 0;
}
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public void setRectangle(double l, double w)
{
length = l;
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double perimeter()
{
return length + width;
}
public double Area()
{
return length*width;
}
**public boolean largerThan(Rectangle r1)
{
if()
return True;
else
return False;
}**
public String toString()
{
return "Length is " + length + " width is " + width;
}
}
public boolean largerThan(Rectangle otherRec){
return this.Area() > otherRec.Area();
}
You can do it like this:
public boolean largerThan(Rectangle r1){
return this.Area() > r1.Area();
}
Your skeleton is basically there, now take the English words of what you want to do:
returns true if the invoking object has a greater area than the object which is the argument and will return false otherwise
And turn it in to code:
public boolean largerThan(Rectangle r1)
{
if(this.Area() > r1.Area())
return True;
else
return False;
}