【发布时间】:2014-09-06 14:23:34
【问题描述】:
我现在正在学习 Java,但遇到了一个问题。该程序决定第三个点是否在笛卡尔坐标系中的矩形内。第一个点是矩形的左上角,第二个点是右下角。您必须像这样输入它:a b c d e f,其中左(a,b)和右(c,d)。 E和f是第三点的点。我希望扫描仪在 6 个整数后停止,因此无需填写非整数,例如“结束”。这是我的代码的一部分:
import java.util.Scanner;
public class Rectangle {
Scanner scanner = new Scanner(System.in);
void insideRectangle() {
int coordinate;
int a;
int b;
int c;
int d;
int e;
int f;
System.out.println("Please fill in the numbers (6 maximum), with spaces in between");
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
while ( scanner.hasNextInt() ) {
coordinate = scanner.nextInt();
a = coordinate;
coordinate = scanner.nextInt();
b = coordinate;
coordinate = scanner.nextInt();
c = coordinate;
coordinate = scanner.nextInt();
d = coordinate;
coordinate = scanner.nextInt();
e = coordinate;
coordinate = scanner.nextInt();
f = coordinate;
}
if ( a > c ) {
System.out.println("error");
} else if ( b < d) {
System.out.println("error");
} else if ( e >= a && c >= e && f <= b && d <= f ) {
System.out.println("inside");
} else {
System.out.println("outside");
}
}
}
【问题讨论】:
-
while循环在 每个 循环通过时读取 6 个坐标。只需杀死循环并保留身体。 (另外,您可以省去重复的coordinate变量,直接分配给a..f,即使是那些也应该重构,但这可能是未来的一段时间。) -
删除循环即可。
-
感谢您的帮助,它成功了。我这周刚开始;-)
标签: java