8. 정수를 몇 개 저장할지 키보드로부터 개수를 입력받아(100보다 작은 개수) 정수 배열을 생성하고, 이곳에 1에서 100까지 범위의 정수를 랜덤하게 삽입하라. 배열에는 같은 수가 없도록 하고 배열을 출력하라.
문제 자체보다 10개씩 출력하는걸 구현하는데 시간을 오래씀
import java.util.Scanner;
public class eight {
public static void main (String[]args) {
Scanner sc=new Scanner(System.in);
System.out.print("정수 몇 개?");
int i=sc.nextInt();
int []a=new int[i];
for(int j=0;j<a.length;j++) {
a[j]=(int)(Math.random()*100)+1;
for(int k=0;k<j;k++){
if(a[k]==a[j])
j--;
}
}sc.close();
int ten=a.length/10;
int start=0;
for(i=0;i<ten;i++) {
for(int j=0;j<10;j++)
System.out.print(a[start+j]+" ");
System.out.println();
start+=10;
}
for(i=start;i<a.length;i++)
{System.out.print(a[i]+" ");}
}
}
16. 컴퓨터와 독자 사이의 가위 바위 보 게임을 만들어보자. 독자가 가위 바위 보 중 하나를 입력하고 <Enter>키를 치면, 프로그램은 가위 바위 보 중에서 랜덤하게 하나를 선택하고 컴퓨터가 낸 것으로 한다. 독자가 입력한 값과 랜덤하게 선택한 값을 비교하여 누가 이겼는지 판단한다. 독자가 가위 바위 보 대신 "그만"을 입력하면 게임을 끝낸다.
import java.util.Scanner;
public class sixteen {
public static void program(String man,int com){//0=바위 1=가위 2=보
if(man.equals("바위")) {
switch(com) {
case 0: System.out.println("사용자 = 바위, 컴퓨터 = 바위, 비겼습니다.");break;
case 1: System.out.println("사용자 = 바위, 컴퓨터 = 가위, 사용자가 이겼습니다.");break;
case 2: System.out.println("사용자 = 바위, 컴퓨터 = 보, 컴퓨터가 이겼습니다.");break;
}
}
if(man.equals("가위")) {
switch(com) {
case 0: System.out.println("사용자 = 가위, 컴퓨터 = 바위, 컴퓨터가 이겼습니다.");break;
case 1: System.out.println("사용자 = 가위, 컴퓨터 = 가위, 비겼습니다.");break;
case 2: System.out.println("사용자 = 가위, 컴퓨터 = 보, 사용자가 이겼습니다.");break;
}
}
if(man.equals("보")) {
switch(com) {
case 0: System.out.println("사용자 = 보, 컴퓨터 = 바위, 사용자가 이겼습니다.");break;
case 1: System.out.println("사용자 = 보, 컴퓨터 = 가위, 컴퓨터가 이겼습니다.");break;
case 2: System.out.println("사용자 = 보, 컴퓨터 = 보, 비겼습니다.");break;
}
}
}
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
while(true) {
System.out.print("가위 바위 보!>>");
String s=sc.next();
if(s.equals("그만"))
break;
int com=(int)Math.random()*3;
program(s,com);
}
System.out.println("게임을 종료합니다...");
sc.close();
}
}
'JAVA > 공부' 카테고리의 다른 글
6. 모듈과 패키지 개념, 자바 기본 패키지 (0) | 2021.01.14 |
---|---|
5. 상속 (0) | 2021.01.14 |
4. 클래스와 객체 (0) | 2021.01.14 |
2. 자바 기본 프로그래밍 (0) | 2021.01.13 |
1. 자바 시작 (0) | 2021.01.13 |