コードでは、実際にgenerateSecretNumber()
メソッドを呼び出すことはなく、代わりに変数を宣言しています。メインの宣言を削除し、印刷行をに変更しますSystem.out.print("Random number is: " + generateSecretNumber());
。
次に、generateSecretNumber()
メソッドは引数を持たないようにする必要があります。これは、メソッドが完全にそれ自体で何を実行するかを決定し、外部データを必要としないためです。int w, x, y, z;
引数がなくなったので、最初に宣言する必要もあります。
次に、上限のないランダムな整数を生成しています。rand.nextInt()
これはあなたが望むものではありません。代わりに、呼び出しの上限は10である必要があり、結果としてrand.nextInt(10)
。これにより、0から9までのランダムな整数が選択されます。
そして最後に、実際の4桁の数字ではなく、数字の合計を返します。代わりに、各桁の合計にその場所を掛けたものを返します。たとえば、4桁目は。である必要がありますw * 1000
。
結果のコード例:
public class RandUniqueFourDigits {
public static void main(String[] args) {
System.out.println("Random number is: " + generateSecretNumber());
}
public static int generateSecretNumber() {
Random rand = new Random();
int w = 0, x = 0, y = 0, z = 0;
// Generate each digit until they're all unique
while(w == x || w == y || w == z || x == y || x == z || y == z) {
w = rand.nextInt(10);
x = rand.nextInt(10);
y = rand.nextInt(10);
z = rand.nextInt(10);
}
// Generate each digit until they're all unique
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w)
// Combine them into one integer and return
return w * 1000 + x * 100 + y * 10 + z;
}
}
そして、より効率的なループ(各番号は、最初のコードのように、必要なときにのみ再生成されます)のために、whileループを完全に次のように置き換えます。
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w);
do y = rand.nextInt(10); while(y == w || y == x);
do z = rand.nextInt(10); while(z == w || z == x || z == y);
その結果:
public class RandUniqueFourDigits {
public static void main(String[] args) {
System.out.println(generateSecretNumber());
}
public static int generateSecretNumber() {
Random rand = new Random();
int w = 0, x = 0, y = 0, z = 0;
// Generate each digit until they're all unique
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w);
do y = rand.nextInt(10); while(y == w || y == x);
do z = rand.nextInt(10); while(z == w || z == x || z == y);
// Combine them into one integer and return
return w * 1000 + x * 100 + y * 10 + z;
}
}