1.아래 가위바위보 프로그램을 짜시오.
- 조건 Main 에서 모든 로직을 짜지 말 것.
- 가위,바위,보에 대한 데이터 멤버를 가진 class 를 기본적으로 만들 것
package array;
import java.util.Random;
import java.util.Scanner;
class Compare {
void rspCompare(String input, String co) {
if (input.equals(co)) {
System.out.println("비겼어요.");
} else if ((input.equals("가위") && co.equals("보")) || (input.equals("바위") && co.equals("가위"))
|| (input.equals("보") && co.equals("가위"))) {
System.out.println("제가 이겼어요~!");
} else {
System.out.println("제가 졌어요ㅠㅠ");
}
}
}
public class rcpTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] str = { "가위", "바위", "보" };
while (true) {
System.out.println("가위 바위 보를 입력하세요.");
System.out.print("나: ");
String input = sc.next();
Random r = new Random();
String co = str[r.nextInt(3)];
System.out.println("컴퓨터: " + co);
Compare c = new Compare();
c.rspCompare(input, co);
System.out.print("계속 하시겠습니까?: ");
String ans = sc.next();
if (ans.equals("y") || ans.equals("yes")) {
} else if (ans.equals("n") || ans.equals("no")) {
System.out.println("안녕히 가세요.");
break;
}
}
}
}
- 출력결과
2. enhanced for문
public class ArrayTest7 {
public static void main(String[] args) {
int[] ar = { 1, 2, 3, 4, 5 };
for (int e : ar) {
System.out.print(e + " ");
}
System.out.println();
int sum = 0;
for (int e : ar) {
sum += e;
}
System.out.println("sum: " + sum);
}
3. 인스턴스 배열 대상 for-each문 (Box형)
class Box {
private String conts;
private int boxNum;
public Box(int num, String conts) {
this.boxNum = num;
this.conts = conts;
}
public String toString() {
return conts;
}
public int getBoxNum() {
return boxNum;
}
}
public class ArrayTest7 {
public static void main(String[] args) {
Box[] ar = new Box[5];
ar[0] = new Box(101, "Coffee");
ar[1] = new Box(202, "Computer");
ar[2] = new Box(303, "Apple");
ar[3] = new Box(404, "Dress");
ar[4] = new Box(505, "Fairy-tale book");
for (Box e : ar) {
if (e.getBoxNum() == 505)
System.out.println(e);
}
}
}