public enum TrafficLight {
RED(20),
YELLOW(3),
GREEN(10);
int duration;
TrafficLight(int newDuraction) {
duration = newDuraction;
}
public int getDuraction() {
return duration;
}
在测试课中它就像:
public class TrafficLightTest {
public static void main(String[] args) {
for (TrafficLight trafficLight : TrafficLight.values()) {
System.out.println(trafficLight.name() + ": duraction " + trafficLight.getDuraction());
}
}
}
我希望例如:" GREEN:duraction 10"数字10就像" **********"。
10 =" **********" (十个星号)
3 =" ***" (三个星号)
我希望你明白这个主意。谢谢:))
答案 0 :(得分:2)
只需使用for循环进行打印" *"所需的次数
System.out.print(trafficLight.name() + ": duraction " ); //change this to Print instead of println
for(int i=0;i<trafficLight.getDuraction();i++)
System.out.print("*");
System.out.println();
希望有所帮助。
答案 1 :(得分:1)
您可以执行以下操作: -
public class TrafficLightTest {
public static String getAsteric(int input){ // return * using the int input
StringBuilder sb = new StringBuilder();
for(int i =0 ; i< input; i++)
sb.append("*");
return sb.toString();
}
public static void main(String[] args) {
for (TrafficLight trafficLight : TrafficLight.values()) {
System.out.println(trafficLight.name() + ": duraction " + TrafficLightTest.getAsteric(trafficLight.getDuraction())); // prints * equal to int input
}
}
}