黑马程序员技术交流社区
标题:
做了个比较完整的随机数生成器
[打印本页]
作者:
ailasanshai
时间:
2016-3-21 20:06
标题:
做了个比较完整的随机数生成器
可以设定生成范围和生成次数了。◕‿◕。
import java.util.Scanner;
class A_Random_Work {
public static void main(String[] args) {
int a1 = 0,b1 = 0;
//0~任意数之间的随机整数
Scanner sc = new Scanner(System.in);
a: while(true) {
System.out.println("要生成0到几的随机数?");
//获得第一个数
//a1 = judge(sc.next());
String a = sc.next();
boolean isNum = a.matches("[0-999999]+");
if(isNum) {
a1 = Integer.parseInt(a);
}
else {
System.out.println("请输入正确的数字\n-------------------------");
continue;
}
//int a = sc.nextInt();
b: while (true) {
System.out.println("-------------------------\n要生成几次?");
//int b = sc.nextInt();
String b = sc.next();
boolean isNum2 = b.matches("[0-999999]+");
if(isNum2) {
b1 = Integer.parseInt(b);
}
else {
System.out.println("请输入正确的数字\n-------------------------");
continue;
}
/*得到要生成的'范围'和要生成的'次数'后
可以开始产生并输出随机数了*/
System.out.println("-------------------------");
for (int i = 0;i < b1 ;i++ ) {
int num = (int)(Math.random()*(a1+1)); //0~a随机数
System.out.print(num+" ");
}
System.out.println();
System.out.println("是否继续生成随机数字? y / n");
String c = sc.next();
if(c.equals("y")|c.equals("Y")) {
System.out.println();
break b;
}
else
break a;
}
}
}
/*public static int judge(String a){
boolean isNum = a.matches("[0-999999]+");
if(isNum) {
return Integer.parseInt(a);
}
else {
System.out.println("请输入正确的数字\n-------------------------");
continue;
}
}*/
}
复制代码
捕获.PNG
(37.39 KB, 下载次数: 36)
下载附件
2016-3-21 20:02 上传
作者:
ailasanshai
时间:
2016-3-21 20:09
生成随机数所用到的一些
Scanner
导包,在 class 之前 import java.util.Scanner;
创建对象,在 main 函数之中 Scanner sc = new Scanner(System.in);
输入数据(字符串型) String a = sc.next();
输入数据(整型) String a = sc.nextInt();
Matcher类
判断字符串是否是正整数 boolean isNum = a.matches("[0-999999]+");
math类
生成随机数random int num = (int)(Math.random()*(a1+1));
其他
将字符串转换为整型 a = Integer.parseInt(b);
比较字符串是否相等 a.equals("Y")
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2