-
输出固定形状整体随机颜色菱形
import java.util.Random;
// 程序输出随机颜色菱形
public class For2 {
public static void main(String[] args) {
Random rand = new Random();
int c = rand.nextInt(31,38);
int num = 35;
// num赋值应为4* -1
for (int i = 1; i <24; i += 2)
{
System.out.printf("%s\033[%dm%s\033[0m%n", " ".repeat(--num),c,"*".repeat(i));
}for (int i = 21; i >=1; i -= 2)
{
System.out.printf("%s\033[%dm%s\033[0m%n", " ".repeat(++num),c,"*".repeat(i));
}
}
}
看同一段代码随机输出不同的颜色
-
java中 repeat循环重复,再上一个程序中【" ".repeat】就是重复输出"空格"
举一个小例子来具体理解下repeat
public class For2 {
public static void main(String[] args) {
System.out.println("今天天气很好".repeat(5));
System.out.println();
System.out.println("今天天气很好 ".repeat(5));
System.out.println();
System.out.printf("今天天气很好%n".repeat(5));
}
}
-
输出固定形状每行随机颜色菱形(把颜色取值放到for循环里面来)
//输出固定形状每行随机颜色菱形
public class For2 {
public static void main(String[] args) {
// 产生随机数
Random rand = new Random();
int num = 35;
// num赋值应为4* -1
for (int i = 1; i <25; i += 2)
{
// (把颜色取值放到for循环里面来)
int c = rand.nextInt(31,38);
System.out.printf("%s\033[%dm%s\033[0m%n", " ".repeat(--num),c,"*".repeat(i));
}for (int i = 21; i >=1; i -= 2)
{
// (把颜色取值放到for循环里面来)
int c = rand.nextInt(31,38);
System.out.printf("%s\033[%dm%s\033[0m%n", " ".repeat(++num),c,"*".repeat(i));
}
}
}