, 당신은 결코 실제로 you'r 대신 변수를 선언, 당신의 generateSecretNumber()
메소드를 호출하지 않습니다. 주 신고를 취소하고 인쇄 라인을 System.out.print("Random number is: " + generateSecretNumber());
으로 변경하십시오.
다음으로 generateSecretNumber()
메서드는 자체적으로 전체 작업을 결정하고 외부 데이터를 필요로하지 않으므로 인수가 없어야합니다. 인수가 없어지기 때문에 int w, x, y, z;
도 선언해야합니다.
둘째, 상한이없는 임의의 정수를 생성합니다. 이것은 원하는 바가 아니며 대신 rand.nextInt()
호출의 상한선이 10이어야하므로 rand.nextInt(10)
이됩니다. 0 ~ 9의 임의의 정수를 선택합니다.
마지막으로 실제 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;
}
}
현재 문제는 무엇입니까? – Gawdl3y
실제로 메소드를 먼저 호출하십시오. 로컬에 저장하지 않아도됩니다. –
어떻게해야합니까 ?? main 메서드에서 secretNumber를 인쇄하고 싶습니다. – user2121773