728x90
반응형
중복을 없애기 위해 이중 반복문을 활용해야 한다.
이때 첫번째 반복문의 변수를 이용해서 유효성 검사하는 방법을 기억해야 한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public class MathMain { | |
// 반환형 : 반환값 없을 경우 | |
public static void main(String[] args) { | |
int[] a = new int[6]; | |
int b = 0; | |
// 배열에 값을 입력하기 위한 반복문 | |
for (int i = 0; i < 6; i++) { | |
a[i] = MathMain.getRandomNumber(); | |
// 아래 반복문에서 한 loop에 두번의 중복을 발견할 경우 | |
// 마지막에 중복 숫자가 다시 나타날 수 있다 (Fail) | |
// 첫번째 반복문을 리셋시키면 중복을 없앨 수 있다. (Success) | |
for (int j = 0; j < i; j++) { | |
if(a[i] == a[j]){ | |
// a[i] = MathMain.getRandomNumber(); | |
i--; | |
} | |
} | |
} | |
// Bonus | |
for (int i = 0; i < 1; i++) { | |
b = MathMain.getRandomNumber(); | |
for (int j = 0; j < 6; j++) { | |
if(b == a[j]) i--; | |
} | |
} | |
// 배열의 값을 출력하기 위한 반복문 | |
for (int i = 0; i < 6; i++) { | |
System.out.print(a[i] + " "); | |
} | |
System.out.println(); | |
System.out.print(b + " "); | |
} | |
// 반환값의 형태가 integer 일 경우 | |
public static int getRandomNumber(){ | |
int result = 0; | |
Random random = new Random(); | |
result = random.nextInt(9) + 1; | |
return result; | |
} | |
} |
728x90
반응형
'Java' 카테고리의 다른 글
콜백(Callback). 알다가도 모르겠구나. (2) | 2017.01.13 |
---|---|
[Java] Abstract 이해하기 (0) | 2016.09.22 |
[Java] 아주 큰 수에서 가장 큰 소인수를 구하는 방법 (0) | 2016.09.08 |
[Java] 지정한 범위 내에서 특정 숫자가 몇번 들어가는지 세는 방법 (0) | 2016.09.06 |
double보다 큰 범주의 수를 관리할 때, BigDecimal (0) | 2016.09.05 |
Comment