如何从布尔值中打印返回值?

时间:2014-10-18 16:13:33

标签: java boolean return-value

我试图从布尔值打印值返回值,以检查if语句是否正常工作。我没有错误但控制台中没有任何显示。任何建议都表示赞赏。

如果它有所不同,代码也不是主类的一部分。如果是,有没有办法从main?

打印布尔值的返回值

这是我尝试过的。

public boolean inCollision(double x, double y, furniture f) {
    if (x + radius <= f.getXpos(0) || x + radius > f.getXpos(2)) {
        System.out.println("False");
        return false;
    }
    if (y + radius < f.getYpos(0) || y + radius > f.getYpos(2)) {
        System.out.println("False");
        return false;
    }
    System.out.println("True");
    return true;
}

这是家具的来源

public class furniture {
	
	private String name;
	private double xpos;
	private double ypos;
	private double width;
	private double height;
	
	
		public furniture (String n, double x, double y, double w, double h)
		{
		name = n;
		xpos = x;
		ypos = y;
		width = w;
		height = h;
	
		}	
		
		public double getXpos(int c){
			if (c==0 || c==1){return xpos;}
			else {return xpos+width;}
			
		}
		
		public double getYpos(int c){
			if (c == 0 || c == 1){return ypos;}
			else {return ypos+width;}
			
		}
		
	
	

		public String toString() {
		  return "the "+ name+ " has a height of "+height+" and a width of "+width+". Its coordinates are ("+xpos+","+ypos+")," ;
		  
		  
		}

		}
		

下面是第一部分的整个代码页。

public class roomba {
	
	private double xpos;
	private double ypos;
	private double radius;
		
	public roomba(double x, double y, double r){
		
		xpos = x;
		ypos = y;
		radius = r;
	}
	
	
	public String toString() {
		  return "the coordinates of the roomba are ("+xpos+","+ypos+").It has a radius of "+radius ;
		  
		  
		}
	
	
	public boolean inCollision(double x, double y, furniture f){
		if (x+radius <=f.getXpos(0) || x+radius >f.getXpos(2)){
			System.out.println("False");
			return false;
		}
		if (y+radius < f.getYpos(0) || y+radius > f.getYpos(2))
		{
			System.out.println("False");
			return false;}
		
		System.out.println("True");
		return true;
	
		


	}
	

1 个答案:

答案 0 :(得分:0)

在您的主要课程中,您必须创建两个对象:roomba和furniture

roomba r = new roomba(1f,1f,1f);
furniture furn = new furniture("chair",2f,2f,2f,2f);

boolean retValBool = r.inCollision(1.5f,1.5f,furn); //
System.out.println(" inCollision method returns : " + retValBool);

在java中,您可以使用相同的方式处理打印所有原始数据类型。这意味着你可以用同样的方式打印整数,双打,布尔等:)