请写一个简单的java方法,长度为7的字符串,前6位数是1--31中的随机数,第7位是1--16的随机数
时间: 2024-06-03 16:12:11 浏览: 10
public String generateRandomString() {
Random random = new Random();
int num1 = random.nextInt(31) + 1;
int num2 = random.nextInt(31) + 1;
int num3 = random.nextInt(31) + 1;
int num4 = random.nextInt(31) + 1;
int num5 = random.nextInt(31) + 1;
int num6 = random.nextInt(31) + 1;
int num7 = random.nextInt(16) + 1;
String result = String.format("%02d%02d%02d%02d%02d%02d%d", num1, num2, num3, num4, num5, num6, num7);
return result;
}
// 使用方法
String randomString = generateRandomString();
System.out.println(randomString); // 可能输出 0102030405067 或 3116172728163 等等
相关问题
写一个长度为7的Java数组,其中前6位数是1到33的随机数,第7位是1到16的随机数,且数组里面的数字不能相同
好的,以下是符合要求的Java代码:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[7];
Random random = new Random();
for (int i = 0; i < 6; i++) {
int num;
do {
num = random.nextInt(33) + 1;
} while (contains(arr, num));
arr[i] = num;
}
int num;
do {
num = random.nextInt(16) + 1;
} while (contains(arr, num));
arr[6] = num;
System.out.println("生成的随机数组为:" + Arrays.toString(arr));
}
private static boolean contains(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
return true;
}
}
return false;
}
}
```
请问还有其他问题吗?
打印一个 长度为7的Java数组,其中前6位数是1到33的随机数,第7位是1到16的随机数,且数组里面的数字不能相同
可以这样实现:
public static void main(String[] args) {
int[] arr = new int[7];
Random random = new Random();
for (int i = 0; i < 6; i++) {
int num;
do {
num = random.nextInt(33) + 1;
} while (contains(arr, num));
arr[i] = num;
}
int num;
do {
num = random.nextInt(16) + 1;
} while (contains(arr, num));
arr[6] = num;
System.out.println(Arrays.toString(arr));
}
private static boolean contains(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
return true;
}
}
return false;
}
希望能够帮助到你,还有什么其它问题可以问我哦~
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)