我现在在学习Java,并且遇到问题。该程序决定第三点是否在笛卡尔坐标系中的矩形内。第一点是矩形的左上角,第二点是右下角。你必须像这样输入:a b c d e f,其中左(a,b)和右(c,d)。 E和f是第三点的要点。我希望扫描器在6个整数后停止,因此不需要填写非整数,如'结束'。这是我的代码的一部分:如何在6次读取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',甚至这些都应该被重构,但这在将来可能会有点用处。) – chrylis 2014-09-06 14:25:51
只需删除循环。 – 2014-09-06 14:27:08
感谢您的帮助,它工作。我刚刚开始这一周;-) – GastonM008 2014-09-06 14:35:47