Java写诗程序
import java.util.Random; public class test_word { public static void main(String[] args) { System.out.println("五言绝句"); System.out.println(); for(int i=0;i<4;i++) { for(int j=0;j<5;j++) { System.out.print(getRandomChineseChar()); } System.out.print("\n"); } System.out.println(); System.out.println("七言律诗"); System.out.println(); for(int i=0;i<8;i++) { for(int j=0;j<7;j++) { System.out.print(getRandomChineseChar()); } System.out.print("\n"); } /* String str = getAllChineseChar(); System.out.println(); System.out.println(str); System.out.println(); System.out.println(getChineseCharCount(str));*/ //如何只取一级汉字??未解决 } //统计汉字字数 public static int getChineseCharCount(String inStr) { int result = 0; String reg = "^[\u4e00-\u9fa5]{1}$"; for(int i=0;i<inStr.length();i++) { String b = Character.toString(inStr.charAt(i)); if (b.matches(reg)) { result ++; } } return result; } //统计汉字字数2 public static int getChineseCharCountEx(String inStr) { int result = 0; char ch; for (int i=0;i<inStr.length();i++) { ch = inStr.charAt(i); if (ch>=19968 && ch <= 64041) { result ++; } } return result; } //获取所有汉字 public static String getAllChineseChar() { String str = ""; byte[] by = new byte[2]; for(int b1 =176;b1<248;b1++) { by[0] = (byte)b1; for(int b2 =161;b2<255;b2++) { by[1]=(byte)b2; try { str += new String(by,"GB2312"); } catch(Exception e) { e.printStackTrace(); } } } return str; } //获取随机汉字 public static String getRandomChineseChar() { String str = ""; int highCode; int lowCode; Random random = new Random(); highCode = (176 + Math.abs(random.nextInt(39))); lowCode = (161 + Math.abs(random.nextInt(93))); byte[] b = new byte[2]; b[0] = Integer.valueOf(highCode).byteValue(); b[1] = Integer.valueOf(lowCode).byteValue(); try { str = new String(b,"GB2312"); } catch(Exception e){ e.printStackTrace(); } return str; } }