本文目錄一覽:
java 隨機輸出10個漢字中的一個,新手求代碼
import java.util.Random;
public class Demo {
public static void main(String[] args) {
String[] str ={“一”,”二”,”三”,”四”,”五”,”六”,”七”,”八”,”九”,”十”};
//演示漢字,裏面的漢字自己更改
Random r= new Random();
int i = r.nextInt(10);
System.out.println(“隨機產生的第”+(i+1)+”位數:”+str[i]);
}
}
如何在java中隨機生成常用漢字
/**
* 原理是從漢字區位碼找到漢字。在漢字區位碼中分高位與底位, 且其中簡體又有繁體。位數越前生成的漢字繁體的機率越大。
* 所以在本例中高位從171取,底位從161取, 去掉大部分的繁體和生僻字。但仍然會有!!
*
*/
@Test
public void create() throws Exception {
String str = null;
int hightPos, lowPos; // 定義高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));//獲取高位值
lowPos = (161 + Math.abs(random.nextInt(93)));//獲取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
str = new String(b, “GBk”);//轉成中文
System.err.println(str);
}
/**
* 旋轉和縮放文字
* 必須要使用Graphics2d類
*/
public void trans(HttpServletRequest req, HttpServletResponse resp) throws Exception{
int width=88;
int height=22;
BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font(“黑體”,Font.BOLD,17));
Random r = new Random();
for(int i=0;i4;i++){
String str = “”+r.nextInt(10);
AffineTransform aff = new AffineTransform();
aff.rotate(Math.random(),i*18,height-5);
aff.scale(0.6+Math.random(), 0.6+Math.random());
g2d.setTransform(aff);
g2d.drawString(str,i*18,height-5);
System.err.println(“:”+str);
}
g2d.dispose();
ImageIO.write(img, “JPEG”,resp.getOutputStream());
}
java產生隨機數我怎麼固定長度
Math.random()返回的只是從0到1之間的小數,如果要50到100,就先放大50倍,即0到50之間,這裡還是小數,如果要整數,就強制轉換int,然後再加上50即為50~100.
最終代碼:(int)(Math.random()*50) + 50
Random random = new Random();//默認構造方法
Random random = new Random(1000);//指定種子數字
在進行隨機時,隨機算法的起源數字稱為種子數(seed),在種子數的基礎上進行一定的變換,從而產生需要的隨機數字。
相同種子數的Random對象,相同次數生成的隨機數字是完全相同的。也就是說,兩個種子數相同的Random對象,第一次生成的隨機數字完全相同,第二次生成的隨機數字也完全相同。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/286705.html