所以,正如您所看到的,我试图在此处设置一些循环,即两个if语句,我在Java脚本中使用了嵌套的for循环,因此我认为这可能行得通,运气不高。
观察第三组,我是用1000 - 10000
做的,所以它是用1000-9999
做的,因为我不知道如何用0000-9999
做它,需要它打印那些0
(电话号码)
我是编程的新学员,所以请对我非常清楚和简单,谢谢。
目标
import java.util.Random;
import java.lang.Math;
public class Main{
public static void main(String[] args){
Random rand= new Random();
int a1 = rand.nextInt(7);
int a2 = rand.nextInt(7);
int a3 =rand.nextInt(7);
int b = rand.nextInt(741);
int c = rand.nextInt(9999);
while (b.length<4)
{
b (string)= "0"+ c ;
}
while (c.length()<4)
{
c (string)= "0"+ c ;
}
System.out.println(a1 +""+ a2+ ""+ +a3+ "-" + b + "-" + c );
}
}
答案 0 :(得分:0)
您只需为 a 执行此操作:
int array[] = {0, 1, 2, 3, 4, 5, 6, 7};
String st = String.format("%d%d%d", array[(int)(Math.random()*8)] , array[(int)(Math.random()*8)] , array[(int)(Math.random()*8)]);
并在控制台中显示输出:
System.out.println(st + "-" + b + "-" + c );
答案 1 :(得分:0)
嗨,这是我到目前为止可以为您提供的服务:
import java.util.Random;
public class HelpYou {
public static void main(String[] args) {
HelpYou helpYou = new HelpYou();
String a1 = helpYou.generateFirstSet();
String a2 = helpYou.generateSecondSet();
String a3 = helpYou.generateThirdSet();
System.out.println("GOAL: XXX-XXX-XXXX");
System.out.println("RESULT: "+a1 + "-" + a2 + "-" + a3);
}
public String generateFirstSet() {
Random rand = new Random();
int a1;
String firstSet = "";
for (int i = 0; i < 3; i++) {
a1 = rand.nextInt(7);
firstSet = firstSet.concat("" + a1);
}
return firstSet;
}
public String generateSecondSet() {
String secondSet = "";
do {
secondSet = generateFirstSet();
// This while solves your constraint :)
} while (Integer.parseInt(secondSet) > 742);
return secondSet;
}
public String generateThirdSet() {
Random rand = new Random();
int a1;
String thirdSet = "";
for (int i = 0; i < 4; i++) {
a1 = rand.nextInt(9);
thirdSet = thirdSet.concat("" + a1);
}
return thirdSet;
}
}
认为这就是您希望对您有所帮助的东西,那就是面向对象的方法,零复杂度,如果您需要我向您澄清任何问题或任何疑问的话。
另外,使用int不可能达到GOAL的方式,因为随机函数永远不会给您0值(093或0094),它只能给您1+个数字(101或10或10)。 1000左右)。我的意思是number = rand.nextInt(9999);
永远不会给您0的数字(0000左右)。因此,您将需要像建立第一组那样自行构造第二组和第三组(这是一个更简单的解决方案):
import java.util.Random;
public class HelpYouSimplier {
public static void main(String[] args) {
Random rand = new Random();
int a1 = rand.nextInt(7);
int a2 = rand.nextInt(7);
int a3 = rand.nextInt(7);
String b = "";
do {
int b1 = rand.nextInt(7);
int b2 = rand.nextInt(4);
int b3 = rand.nextInt(2);
b = "" + b1 + b2 + b3;
} while (Integer.parseInt(b) > 742);
// Variables for third set
int c1 = rand.nextInt(9);
int c2 = rand.nextInt(9);
int c3 = rand.nextInt(9);
int c4 = rand.nextInt(9);
String c = "" + c1 + c2 + c3 + c4;
System.out.println(a1 + "" + a2 + "" + +a3 + "-" + b + "-" + c);
}
}