과제
//402호 전체 학생들 중 사용자가 입력한 숫자만큼 랜덤으로 학생을 뽑는 프로그램을 만들어주세요.
String[] students = { "강나영", "강동환", "강태영", "곽지훈", "김서윤"
, "김영훈", "김진석", "김충신", "박슬기", "박채린"
, "손영태", "손영흔", "안정연", "이선우", "이수보"
, "이주홍", "이중호", "임현정", "장유진", "정신애"
, "조수경", "조하영", "조혜민", "허민정", "박지은"};
선생님 답 :
Scanner s = new Scanner(System.in);
System.out.print("몇명?");
int count = Integer.parseInt(s.nextLine());
String[] pick = new String[count]; //뽑은 사람을 저장할 배열
int pickCount = 0; // 현재 뽑은 사람 수
do{
int random = (int)(Math.random() * students.length);
boolean flag = true;
for(int i = 0; i < pick.length; i++){
if(students[random].equals(pick[i])){ //랜덤으로 뽑힌 사람과 이미 뽑힌 사람과 같으면 flag = false
flag = false;}
}
if(flag){
pick[pickCount++] = students[random]; flag = true일때만(중복이 아닐때만) pick이라는 배열에 이름을 저장
}
}while(pickCount < count);
System.out.println(Arrays.toString(pick));
내 답 :
Scanner s = new Scanner(System.in);
System.out.print("뽑을 학생 수를 입력해주세요>");
int input = Integer.parseInt(s.nextLine());
int random = 0;
String a = null;
for(int i = 0; i < input; i++){
int x = students.length - 1 - i;
random = (int)(Math.random() * (students.length - i)); //random의 값이 중복되지 않게
System.out.print(students[random]);
a = students[x];
students[x] = students[random];
students[random] = a;
System.out.print("/");
거스름돈 구하기
int money = (int)(Math.random() 500) 10;
int[] coin = { 500, 100 ,50 ,10 };
System.out.println("거스름돈 : " + money + "원");
for(int i = 0; i < coin.length; i++){
int count = money / coin[i]; //거스름돈 / 500원을 한 값 거스름돈 / 100원 한 값
money %= coin[i]; //나머지돈
System.out.println(coin[i] + "원 : " + count + "개" );
}
1~5의 숫자가 발생된 횟수 만큼 *을 사용해 그래프를 그려주세요.
*
* 1: *** 3
* 2: **** 4
* 3: ** 2
* 4: ***** 5
* 5: ****** 6
*
*/
int[] arr = new int[20];
for(int i =0; i < arr.length; i++){
arr[i] = (int)(Math.random() * 5) + 1;
}
System.out.println(Arrays.toString(arr));
답:
int[] count = new int[5]; //{ 1,0,0,0,0} = count[1]
for(int i = 0; i <arr.length; i++){
count[arr[i] - 1]++; //인덱스 값을 구해야해서 -1 해줌
}
for (int i =0; i < count.length; i++){
System.out.print(i + 1 + " : ");
for(int j = 0; j <count[i]; j++){
System.out.print("*");
}
System.out.println(" "+ count[i]);
오늘의 과제:
1~5 사이의 랜덤한 값이 10개 저장된 배열에서 중복된 값이 제거된 배열을 만들어주세요.
[3,2,3,2,3,4,5,5,2,4]
[3,2,4,5]
선생님 답)
Scanner s = new Scanner(System.in);
System.out.print("몇명?");
int count = Integer.parseInt(s.nextLine());
String[] pick = new String[count]; //뽑은 사람을 저장할 배열
int pickCount = 0; // 현재 뽑은 사람 수
do{
int random = (int)(Math.random() * students.length);
boolean flag = true;
for(int i = 0; i < pick.length; i++){
if(students[random].equals(pick[i])){ //랜덤으로 뽑힌 사람과 이미 뽑힌 사람이 같으면 flag = false
flag = false;}
}
if(flag){
pick[pickCount++] = students[random]; flag = true일때만(중복이 아닐때만) pick이라는 배열에 이름을 저장
}
}while(pickCount < count);
System.out.println(Arrays.toString(pick));