此为主函数
public class AppClass {
public static void main(String[] args)
{ TestClass test = new TestClass();
for(int i = 0 ;i<10;i++){
String str = test.get(10);
System.out.println(str);
}
}
}此为调用函数
生成随机数的函数public class TestClass {
public String get(int len)
{String str = "";
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Random r = new Random(System.currentTimeMillis());
Random r2 = new Random(System.currentTimeMillis());
int len2 = r.nextInt(len);
for(int i=0;i<len2;i++)
{
int a = r.nextInt(10);
String s = Integer.toString(a);
str += s;
}
return str;
}
}8500
96592
9
27
758
02681
97857488
11104641
这是十个显示的随机数
可是 会有一个随机数是NULL
即 上面第八行
能不能解决 循环出每一行都是有数字的randomjavaJ2SE
public class AppClass {
public static void main(String[] args)
{ TestClass test = new TestClass();
for(int i = 0 ;i<10;i++){
String str = test.get(10);
System.out.println(str);
}
}
}此为调用函数
生成随机数的函数public class TestClass {
public String get(int len)
{String str = "";
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Random r = new Random(System.currentTimeMillis());
Random r2 = new Random(System.currentTimeMillis());
int len2 = r.nextInt(len);
for(int i=0;i<len2;i++)
{
int a = r.nextInt(10);
String s = Integer.toString(a);
str += s;
}
return str;
}
}8500
96592
9
27
758
02681
97857488
11104641
这是十个显示的随机数
可是 会有一个随机数是NULL
即 上面第八行
能不能解决 循环出每一行都是有数字的randomjavaJ2SE
if (str == null || str.equals("") {
str = get(len);
}
int len2 = r.nextInt(len); //此处len2值可能为0,此时循环不会执行,str值为Null
for(int i=0;i<len2;i++)
{
int a = r.nextInt(10);
String s = Integer.toString(a);
str += s;
}
return str;2、调整后的代码,请参考(见注释说明)package com.zl.base;import java.util.Random;public class RandomDemo { /**
* @param args
*/
public String get(int len){
String str = "";
Random r = new Random(System.currentTimeMillis());
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random r2 = new Random(System.currentTimeMillis());
int len2 = r.nextInt(len); //此处len2的值可能为0,故下面的for循环可能不执行,加上一个值是否为0的判断,可解决该问题
if(len2 == 0) { //bugfixed;len2为0时,给str赋值为“0”,避免值为null的情况出现
str = "0";
}else {
for(int i=0;i<len2;i++) {
int a = r.nextInt(10);
String s = Integer.toString(a);
str += s;
}
}
return str;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomDemo demo = new RandomDemo();
for(int i = 0;i < 10;i++) {
String str = demo.get(10);
System.out.println(str);
}
}}