随机颜色

此博客展示了一段Java代码,用于生成随机十六进制颜色代码。通过伪随机数生成器,计算RGB值并转换为十六进制字符串,存储在ArrayList中。最后将生成的颜色代码以表格形式输出,可生成指定数量的不重复颜色代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%@ page import="java.util.*" %>

<%!
public ArrayList getRandomHexColor(int colorCount) throws Exception
{
   ArrayList colorList = new ArrayList(colorCount);
   try
   {
       Random random = new Random(0L);//pseudorandom number generator
       for(int i=0;i<colorCount;i++)
       {
          random.nextFloat();//the next pseudorandom
          int colorR = Math.round(255-random.nextFloat()*255);
          int colorG = Math.round(255-random.nextFloat()*255);
          int colorB = Math.round(random.nextFloat()*255);
          //hex color string
          String color = parseString(colorR)+parseString(colorG)+parseString(colorB);
          if(!colorList.contains(color))
          {
             colorList.add(color);
          }
          else
          {
             colorCount+=1;
          }
       }//end for
   }
   catch(Exception ex)
   {
      throw ex;
   }
   return colorList;
}
public String parseString(int data)
{
   String str = Integer.toHexString(data);
   if(str.length()==1)
   {
      str = "0"+str;
   }
   return str;
}
%>

<%
//Use pseudorandom number generator
out.println("<table border=0 align='left'>");

ArrayList colorAryList =  getRandomHexColor(100);
for(int i=0,j=colorAryList.size();i<j;i++)
{
  String color = "#"+(String)colorAryList.get(i);
  if(i%8==0)
     out.println("<tr>");
  out.println("<td bgcolor=/"#"+color+"/">Mode"+(i+1)+" : "+color+"<td>");
}
out.println("</table>");


%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值