[英]How to compare values generated in a for loop without using an array
您好,我正在創建一個程序,詢問用戶要在程序中輸入多少個矩形。 然后,我在一個for
循環中使用此數字,該循環在詢問用戶每個矩形的名稱以及矩形上2個角的坐標時循環。 在此for
循環中,在用戶輸入所有這些數據之后,我想比較這些點以查找哪個矩形具有最大/最小面積和周長,而無需使用數組。 這是我的代碼的一部分:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
process(s);
}
public static void process(Scanner s) {
System.out.println("Please enter the number of rectangles as an integer");
int rectnum;
rectnum = s.nextInt();
for(int i = 0; i<rectnum; i++){
System.out.println("PLease enter the rectangle's name as a single letter");
String rectname;
rectname = s.next();
System.out.println("Please enter the x value of one coordinate
of the rectangle" );
int xcoor1;
xcoor1 = s.nextInt();
System.out.println("Please enter the y value of the same coorinate
of the rectangle");
int ycoor1;
ycoor1 = s.nextInt();
System.out.println("Please enter the x value of annother
coordinate of the rectangle");
int xcoor2;
xcoor2 = s.nextInt();
System.out.println("Please enter the y value of the same
coordinate of the rectangle");
int ycoor2;
ycoor2 = s.nextInt();
int Perim;
Perim = 2 *(java.lang.Math.abs(ycoor1 - ycoor2)+
java.lang.Math.abs(xcoor1 - xcoor2));
int Area;
Area = java.lang.Math.abs((ycoor1 - ycoor2) * (xcoor1 - ycoor2));
/*
* ....
*/
}}
我建議您從Rectangle
POJO開始
public class Rectangle {
private final char name;
private final int x1;
private final int x2;
private final int y1;
private final int y2;
public Rectangle(char name, int x1, int x2, int y1, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.name = name;
}
@Override
public String toString() {
return String.format("%s : (%d, %d) (%d, %d)",
Character.toString(name), x1, y1, x2, y2);
}
// ...
}
當然...
可以是您想要的任何其他方法。
您可以創建一個名為Rectangle的類,該類存儲相關的值以及矩形的名稱。 在該類中創建4個對象,並將它們稱為maxArea,minArea,maxPerimeter和minPerimeter。 遍歷用戶輸入時,一旦遇到新的最大面積,最小面積,最小周長或最大周長,請替換對象的相關值。
這種方法的優點是,無論用戶輸入多少矩形,其空間要求都是恆定的。
試試這個
int pMax=Integer.MIN_VALUE,pMin=Integer.MAX_VALUE;
int aMax=Integer.MIN_VALUE,aMin=Integer.MAX_VALUE;
在循環內部,在計算了輸入矩形的面積和周長之后,可以將其與現有的最大值和最小值進行比較,並根據需要進行更新。
即:
if(area<aMin)
aMin=area;
if(area>aMax)
aMax=area;
if(perim<pMin)
pMin=perim;
if(perim>pMax)
pMax=perim;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.