如果声明似乎正在跳过其他

如果声明似乎正在跳过其他

本文介绍了如果声明似乎正在跳过其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,用于确定圆圈是否在内部/触摸矩形。用户放入圆的中心点和半径,以及矩形的两个对角点。

I'm trying to write a program that decides whether a circle is inside/touching a rectangle. The user puts in the center point for the circle and the radius, and two diagonal points for the rectangle.

我不确定如何包含圆周长的所有点,以告知矩形中至少有一个点/接触矩形。任何人都知道如何做到这一点?

I'm not sure how to include all points of the circumference of the circle, to tell that there is at least one point in/touching the rectangle. Anyone sure how to do this?

当我运行当前程序时,我会故意输入一个矩形内部的圆点,并且应该使用if我提出的陈述,但它打印出错误的答案。

When I run my current program, I'll purposely enter points of a circle being inside of a rectangle, and should work with the if statements I put, but it prints out the wrong answer.

import java.util.Scanner;
public class lab4 {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    double cx, cy, x, y, r, p1x, p1y, p2x, p2y, max;//input
    String a;

    System.out.print("Enter cx: ");
    cx = in.nextDouble();
    System.out.print("Enter cy: ");
    cy = in.nextDouble();
    System.out.print("Enter r: ");
    r = in.nextDouble();

    System.out.println("Enter x value of point 1:");
    p1x = in.nextDouble();
    System.out.println("Enter y value of point 1:");
    p1y = in.nextDouble();
    System.out.println("Enter x value of point 2:");
    p2x = in.nextDouble();
    System.out.println("Enter y value of point 2:");
    p2y = in.nextDouble();


    max = p2x;
    if (p1x > max)
        max = p1x;

    max = p2y;
    if (p1y > max)
        max = p1y;

    if (cx >= p1x && cx <= p2x)
        a = "Circle is inside of Rectangle";
    if (cx >= p1x && cx <= p2x)
        a = "Circle is inside of Rectangle";
    if (cx+r >= p1x && cx+r <= p2x)
        a = "Circle is inside of Rectangle";
    if (cx-r >= p1x && cx-r <= p2x)
        a = "Circle is inside of Rectangle";
    if (cy >= p1y && cy <= p2y)
        a = "Circle is inside of Rectangle";
    if (cy >= p1y && cy <= p2y)
        a = "Circle is inside of Rectangle";
    if (cy+r >= p1y && cy+r <= p2y)
        a = "Circle is inside of Rectangle";
    if (cy-r >= p1y && cy-r <= p2y)
        a = "Circle is inside of Rectangle";
    else
        a = "Circle is outside of Rectangle";

    System.out.println(a);


推荐答案

您的else语句仅以最后一条if语句为条件。因此,如果最后一个if语句为false,则会执行else语句。你可能想要:

Your else statement is only conditional on the last if statement. So if the last if statement is false, your else statement gets executed. You probably instead want:

if ...
else if ...
else if ...
else

只有在以前所有if语句都为假的情况下才执行else 。

which executes the else only if all the previous "if" statements are false.

这篇关于如果声明似乎正在跳过其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 20:06