所以这是我制作一堆桌子的代码。(我还是初学者)
import java.applet.Applet;
import java.awt.*;
public class Test extends Applet{
public void init() {
setSize(500, 225);
}
public void paint (Graphics g){
//Desk #1
int [ ] x8 = {430, 430, 351, 351};
int [ ] y8 = {200, 185, 185,200};
g.drawPolygon(x8, y8, 4);
//Desk #2
int [ ] x9 = {351, 351, 272, 272};
int [ ] y9 = {200, 185, 185, 200};
g.drawPolygon(x9, y9, 4);
//Desk #3
int [ ] x10 = {272, 272, 193, 193};
int [ ] y10 = {185, 200, 200, 185};
g.drawPolygon(x10, y10, 4);
//Desk #4
int [ ] x11 = {193, 193, 114, 114};
int [ ] y11 = {185, 200, 200, 185};
g.drawPolygon(x11, y11, 4);
//Desk #5
int [ ] x12 = {114, 114, 35, 35};
int [ ] y12 = {185, 200, 200, 185};
g.drawPolygon(x12, y12, 4);
}
}
我想要做的只是做一个while循环所以然后我不需要做所有这些序列垃圾,有人可以为我做一个有效的while循环代码并教我如何做它,我已经坚持了很久。
答案 0 :(得分:1)
您可以使用内部类来存储坐标。我不确定你是否想要专注于多维数组。
public class Test extends Applet {
Poly desk1 = new Poly(new int[] {430, 430, 351, 351}, new int[] {200, 185, 185,200});
Poly desk2 = new Poly(new int[] {351, 351, 272, 272}, new int[] {200, 185, 185, 200});
Poly desk3 = new Poly(new int[] {272, 272, 193, 193}, new int[] {185, 200, 200, 185});
Poly desk4 = new Poly(new int[] {193, 193, 114, 114}, new int[] {185, 200, 200, 185});
Poly desk5 = new Poly(new int[] {114, 114, 35, 35}, new int[] {185, 200, 200, 185});
Poly[] desks = new Poly[] {desk1, desk2, desk3, desk4, desk5};
public void init() {
setSize(500, 225);
}
public void paint (Graphics g) {
for (int i = 0; i < desks.length; i++) {
g.drawPolygon(desks[i].xs, desks[i].ys, 4);
}
}
private static class Poly {
// public fields are sometimes frowned upon,
// but for a private class and a simple example
public int[] xs;
public int[] ys;
public Poly(int[] xs, int[] ys) {
this.xs = xs;
this.ys = ys;
}
}
}
答案 1 :(得分:0)
为什么不这样做,而不是为每个坐标设置单独的数组:
int[][] x = {
{123, 534, 643},
{123, 543, 152},
...
{543, 125, 163}
};
int[][] y = {
{123, 534, 643},
{123, 543, 152},
...
{543, 125, 163}
};
现在你只需要迭代这些使用循环。请记住,隐含的假设似乎是x和y都具有相同的坐标数,因此您应该能够同时迭代它们两个以获得相应的x
和{ {1}}的
要求你为你编写代码可能不会起作用,因为我们并没有真正给出代码,除非你表现出很重要的工作。
答案 2 :(得分:0)
我不会给你答案,但这可能会有所帮助。创建一个二维数组int [] [],其中x为大小[4] [4],y为[4] [4]。
然后你可以创建一个while循环来迭代数组。即使是for循环也足够好。
类似这样的事情
for(int i = 0 ; i < 4; i++) {
g.drawPolygon(x[i], y[i]);
}
for(int i = 0 ; i < 4; i++) {
g.drawPolygon(x[i], y[i]);
}
答案 3 :(得分:0)
这是一种使用简单数学计算坐标的替代解决方案。
public class Test extends Applet {
public void init() {
setSize(500, 225);
}
public void paint(Graphics g) {
int deskCount = 5;
int[] y = { 200, 185, 185, 200 };
for (int i = 0; i < deskCount; i++) {
int[] x = { 430 - i * 79, 430 - i * 79, 351 - i * 79, 351 - i * 79 };
g.drawPolygon(x, y, 4);
}
}
}
答案 4 :(得分:0)
感谢大家的工作,它确实有所帮助,所以谢谢你和最后一个人,for循环也是很棒的方式,但在那个时候我设法通过一个while循环找到了如何做到这一点,如下所示! :)
//Desk #1-4 #Using While Loop
int c=0;
int [ ] x1 = {65, 65, 153, 153};
int [ ] y1 = {20, 35, 35, 20};
g.drawPolygon(x1, y1, 4);
while (c <= 3) {
g.drawPolygon(x1, y1, 4);
x1[0] += 88;
x1[1] += 88;
x1[2] += 88;
x1[3] += 88;
c += 1; // c = c + 1; - Same thing.
}