I am trying to write a method that takes two rectangle parameters, and will return true if the first rectangle fits inside the second rectangle and false if it doesn't.
import java.awt.Rectangle;
public class Square {
public static void main (String[] args) {
Rectangle rect1 = new Rectangle(0,0,100,200);
Rectangle rect2 = new Rectangle(0,0,100,200);
fitsInside(rect1, rect2);
}
public static boolean fitsInside(Rectangle rec1, Rectangle rec2) {
if (rec1.width < rec2.width && rec1.height < rec2.height) {
return true;
} else {
return false;
}
}
}
When I compile and run this code it returns nothing. Why does this not work and how I could fix it?
Your approach is right. The thing is you're not outputting your answer.
Surround the line where you call fitsInside with System.out.println(...) and it will display the result you're computing.
The function fitsInside returns a boolean variable, but you are not using its return value. Since you haven't printed anything, you didn't get the result.
Printing the result will solve your problem:
System.out.println(fitsInside(rect1, rect2));
Related
Newbie completeing thinkJava book and trying to figure out one of the answers to the exercises. It calls for me to download the "GridWorld" files and complete the following steps:
Write a method named moveBug that takes a bug as a
parameter and invokes move. Test your method by calling it from main.
Modify moveBug so that it invokes canMove and moves the bug only if
it can.
Modify moveBug so that it takes an integer, n, as a parameter, and
moves the bug n times (if it can).
Modify moveBug so that if the bug can’t move, it invokes turn instead.
I am stuck on number 3, I can not figure out how to pass n into the "move() method"
-Please Help I am a newbie
My Code:
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;
public class BugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Bug redBug = new Bug();
world.add(redBug);
world.add(new Rock());
world.show();
moveBug(redBug,5);
System.out.println(redBug.getLocation());
}
public static void moveBug(Bug aBug, int n){
if(aBug.canMove() == true){
aBug.move();
} else {
aBug.turn();
}
}
}
You mean you're stuck on number 3:
Modify moveBug so that it takes an integer, n, as a parameter, and moves the bug n times (if it can).
This means write a loop, looping n times, calling move() once per iteration, if canMove() returns true.
BTW: if (canMove() == true) {...} is the long way to say if (canMove()) {...}.
And fix the indentation of the if statement.
Thanks for pointing me #Andreas
My Solution that worked:
public static void moveBug(Bug aBug, int n){
for(int i = 0; i < n; i++){
if(aBug.canMove())
{
aBug.move();
} else {
aBug.turn();
}
}
}
Basicly I am creating a game that you click on falling objects, E.G cookies, and I need to know how to check and see if a certain cookie has been pressed so it can disappear but the problem is that its in an array.
Here is a bit of my code:
Input class...
public class Input implements MouseListener, MouseMotionListener{
#Override
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(MainGame.CG)){
if(MainGame.MG.inGame){
//There is actually something else here but its classified (haha sorry about that)
if(e.getPoint().x > /*I NEED SOMETHING HERE*/){
//tells you if the object has been pressed
MainGame.CG.cookieClicked = true; //CG = ClickerGame
}
}
}
}
}
class with array...
public class ClickerGame extends JPanel{
public int amount;
public FallingObject[] fo = new FallingObject[120]; //THE ARRAY I'M HAVING TROUBLES WITH
/*THE REST IS A SECRET (SORRY ABOUT THAT)*/
}
If you don't understand here is a picture to demonstrate what I need...
In order to avoid having to check the coordinates of 120 different items on each click, make every element inside FallingObject[] aware of three things:
Its own area of influence (see sn00fy's answer)
The containing class (in this case probably ClickerGame
Its location in the array (an int)
To do this, you would need to change your FallingObject constructor to look something like this:
public void FallingObject(ClickerGame master, int index); //add whatever else is needed for Falling Object.
Then you could instantiate the array as follows.
for(int i = 0; i < 120; i++) {
fo[i] = new FallingObject(this, i ); //add anything else needed for the constructor
}
Then each FallingObject is responsible for its own state, and when clicked it is able to report back to the ClickerGame instance. All you need now is a method in ClickerGame which each FallingObject can call.
public void clickedObj(int index) {
FallingObject temp = null;
if(index >= 0 && index < 120) {
temp = fo[index];
//Do stuff with temp :)
}
}
To call this method from within FallingObject just reference the 'master' variable (which you should probably save as a global variable within the class.
You have to check every element in your FallingObject[] array if it intersects with the mouse pointer coordinates at the moment of the click.
You can implement a simple rectangle test or use a circle for each cookie as explained here:
Equation for testing if a point is inside a circle
I have a Sudoku puzzle solver that requires us to use recursion.. The problem is my boolean to check for available space is supposed to update the current position by reference and it is not. What would cause this?
public boolean solve()
{
Coordinate current = new Coordinate();
if (findEmptyGridSlot(current)) { // THE ERROR IS HERE ********** THIS IS SHOWING (0,0) STILL ******************
for (int number = 1; number <= 9; number++)
if (canPlaceNumber(current, number)) {
grid[current.getRow()][current.getColumn()] = number;
if (solve())
return true;
grid[current.getRow()][current.getColumn()] = 0;
} return false;
}else
return true;
}
private boolean findEmptyGridSlot(Coordinate coordinate)
{
boolean found = false;
try{
while (!found)
{
if (grid[coordinate.getRow()][coordinate.getColumn()] == 0)
found = true;
else
coordinate = coordinate.next(); // *****This is supposed to update the current coordinate ******
}
}catch (Exception e){
//CREATE No Empty Cells Exception
}
return found;
}
public Coordinate next()
{
Coordinate result = new Coordinate(row, column);
result.column++;
if (result.column > MAX_COORDINATE)
{
result.column = MIN_COORDINATE;
result.row++;
if (result.row > MAX_COORDINATE) result = null;
}
return result;
}
Java passes by value. This means you are getting a copy of the reference to coordinate. If you point that copy to a new object (i.e. coordinate = coordinate.next) you are only changing the local copy. Now, on the other hand, if you changed an attribute of the object your variable refers to (e.g. coordinate.x = foo or coordinate.setX(foo)) that change will be visible to the caller of your method.
jpm is correct, but I misread the first time so i'm going to try to clarity
private boolean findEmptyGridSlot(Coordinate coordinate)
A reference is passed by value. Think in these terms "coordinate" is a box that holds a piece of paper, on the piece of paper an address is written. coordinate is a box that belongs to only this method and it has its own piece of paper (many pieces of paper may have the same address written on them)
We can look in this box and 'post' things to the address written on the piece of paper, however when we say
coordinate=something
this means write on a new piece of paper the address of 'something'. Throw away the old piece of paper.
This action in no way affects the original 'house' that the first piece of paper had the address on. When my friend Jon updates his address book it doesn't matter what he writes, I still live in my house.
So, if coordinate has some easy substructure (eg x and y) you can 'post' an instruction to change x and y to be equal to the "next" one.
Or as a hack you can enclose a Coordinate inside annother object so you can post an instruction to it to change what the hack class points to
Test Code refered to in comments:
public class Test {
public static void main(String args[]){
String bareMinObject="start";
changeString(bareMinObject);
System.out.println(bareMinObject); //Prints start, change string has no effect
}
public static void changeString(String input){
String temp="end";
input=temp;
}
}
I have a program that allows you to move various Shapes about. I want to be able to return a boolean that returns true if two shapes are intersecting. This is what I have thus far:
public boolean overlaps(MyShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
PathIterator pi = path.getPathIterator(null);
return path.intersects(pi,otherShapeBoundary);
}
...where path is a GeneralPath (these are all straight from the API, except MyShape).
One thing I'm unsure on is how PathIterator works, which might be the problem. I've also tried this, but I was getting a similar error:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
The error is that this method almost always returns false. I'm unsure when/why it is returning true, but it is very infrequent.
What I tried second was actually the correct answer. Just to be clear:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
is the best method of determining intersection.
I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).