所以我有这个代码创建2个矩形并返回长度,宽度和颜色 但是,我想这样做,它创建了用户在" nbRect"中输入的矩形数量。变量。 这是我的代码:
view
} class Rectangle {
package ca.qc.bdeb.info202.exercises;
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
double longeur;
double largeur;
String couleur;
int nbRect;
System.out.println("How many rectangles do you want to create ?");
nbRect = read.nextInt();
Rectangle rect1 = new Rectangle(); //Here is the problem i think, i want it to make as many rectangles as the "nbRect" variable value.
System.out.println("Enter the color, the length and the width of the rectangle : ");
couleur = read.nextLine();
rect1.setCouleur(couleur);
longeur = read.nextInt();
rect1.setLong(longeur);
largeur = read.nextInt();
rect1.setLarg(largeur);
System.out.println("Rectangle 1 -- Long: " + rect1.getLong() + ", Larg: " + rect1.getLarg() + ", Couleur: " + rect1.getCouleur());
}
答案 0 :(得分:0)
我在代码中修改了一些内容。我测试了它,它应该按照你的期望工作。
package ca.qc.bdeb.info202.exercises;
import java.util.*;
public class TestRectangle {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
double longeur;
double largeur;
String couleur;
int nbRect;
List<Rectangle> rectangles = new ArrayList<Rectangle>();
System.out.println("How many rectangles do you want to create ?");
nbRect = read.nextInt();
for(int i = 1; i <= nbRect ; i++){
Rectangle rect1 = new Rectangle();
System.out.println("Enter the color of the rectangle : ");
couleur = read.next();
rect1.setCouleur(couleur);
System.out.println("Enter the length of the rectangle : ");
longeur = read.nextInt();
rect1.setLong(longeur);
System.out.println("Enter the width of the rectangle : ");
largeur = read.nextInt();
rect1.setLarg(largeur);
rectangles.add(rect1);
}
int rectNumber = 1;
for(Rectangle rect : rectangles){
System.out.println("Rectangle: "+ rectNumber +" -- Long: " + rect.getLong() + ", Larg: " + rect.getLarg() + ", Couleur: " + rect.getCouleur());
rectNumber++;
}
}
}
class Rectangle {
private double largeur = 1;
private double longeur = 1;
private String couleur = "white";
public Rectangle() {
}
public Rectangle(double largeur, double longeur, String couleur) {
this.couleur = couleur;
this.largeur = largeur;
this.longeur = longeur;
}
public double getLarg() {
return largeur;
}
public double getLong() {
return longeur;
}
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur){
this.couleur = couleur;
}
public void setLong(double longeur){
this.longeur = longeur;
}
public void setLarg(double largeur){
this.largeur = largeur;
}
}