import java.util.Random;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
int max = 0, min = 0;
int[] num = new int[10];
Random ran = new Random();
Scanner sc = new Scanner(System.in);
System.out.print("최대 정수를 입력하세요: ");
max = sc.nextInt();
System.out.print("최소 정수를 입력하세요: ");
min = sc.nextInt();
for(int j = 0; j < 10; j++) {
num[j] = ran.nextInt(max - min + 1) + min;
} //최대 - 최소 + 1 +최
for(int i = 0; i < 10; i++) {
System.out.print(num[i] + " ");
}
}
}

import java.util.Random;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int start = 0, end = 0;
start = sc.nextInt();
end = sc.nextInt();
for(int i=0;i<10;i++)
System.out.println(rand.nextInt(end-start+1)+start);
for(int i=0;i<10;i++)
System.out.println((int)(Math.random()*(end-start+1))+start);
}
}
1.Lotto 자동생성기(1차원 배열) 5셋트
2.빈 배열에 1부터 45까지 순서대로 넣은 후, 섞기(shuffle)
3.Lotto 자동생성기(2차원 배열) 5셋트
public class Practice {
public static void main(String[] args) {
int cnt = 0;
Random ran = new Random();
int[] lottoNum = new int[6]; // 로또 한줄 5세트면 5개
int[][] lotto = new int[6][5];// 3번
while (cnt < 5) {
for (int i = 0; i < lottoNum.length; i++) {
lottoNum[i] = ran.nextInt(45) + 1;
for (int j = 0; j < i; j++) {
if (lottoNum[i] == lottoNum[j]) {
i--;//삭제되는 배열에 -1 하면 위로 올라가서 다시 증감되서 삭제된 배열에 다시 값 지
}
}
}
cnt++;
Arrays.sort(lottoNum);
for (int a = 0; a < lottoNum.length; a++) {
System.out.print(lottoNum[a] + " ");
}
System.out.println();
}
System.out.println("====================");
for (int i = 0; i < lotto.length; i++) {
for (int j = 0; j < lotto[i].length; j++) {
lotto[i][j] = ran.nextInt(45) + 1;
for (int a = 0; a < j; a++) {
if (lotto[i][j] == lotto[i][a]) {
j--;//해당 배열 삭제시키고, 삭제시킨 배열부터 다시 삽입
}
}
}
}
for (int i = 0; i < lotto.length; i++) {
for (int j = 0; j < lotto[i].length; j++) {
System.out.print(lotto[i][j] + " ");
}
System.out.println();
}
}
}

package com.test.memo;
import java.util.Arrays;
import java.util.Random;
class Lotto {
private int[] lotto;
private Random random;// 난수 생성을 위한
private final int MAX = 6;
Lotto() {
lotto = new int[MAX];
random = new Random();
}
public void execute() {// 메소드 호출
makeLotto();
sortLotto();
printLotto();
}
public boolean chkNum(int idx) {// 배열에 있는 값이 중복되는지 안되는지
for (int i = 0; i < idx; i++) {
if (lotto[idx] == lotto[i]) {
return false;
}
}
return true;
}
public void makeLotto() {// 로또번호 난수 생성
for (int i = 0; i < lotto.length; i++) {
lotto[i] = random.nextInt(45) + 1;
if (!chkNum(i)) {// 메소드 호출해서 값이 중복되면, 삭제
i--;
}
}
}
public void sortLotto() {
Arrays.sort(lotto);
/*
* 정렬
for(int i=0;i<lotto.length-1;i++) {
for(int j=i+1;j<lotto.length;j++) {
if(lotto[i]>lotto[j]) {
tmp = lotto[i]; lotto[i] = lotto[j]; lotto[j] = tmp;
}
}
}
*/
}
public void printLotto() {
for (int i : lotto) {
System.out.println(i + " ");
}
}
}
public class Practice {
public static void main(String[] args) {
Lotto lotto = new Lotto();
for (int i = 0; i < 5; i++) {
lotto.execute();
}
}
}
import java.util.Arrays;
import java.util.Random;
class Lotto
{
private int[] lotto;
private int[] number;
private Random random;
private final int MAX = 6;
private final int RANGE = 45;
Lotto()
{
number = new int[RANGE];
lotto = new int[MAX];
random = new Random();
for(int i=0;i<number.length;i++)
number[i] = i+1;
}
public void execute()
{
shuffle();
sortLotto();
printLotto();
}
public void shuffle()
{
for(int i=0;i<RANGE;i++)
{
for(int j=0;j<10;j++)
{
int k = random.nextInt(45);
int temp = 0;
temp = number[i];
number[i] = number[k];
number[k]= temp;
}
}
System.arraycopy(number, 0, lotto, 0, MAX);
/*
for(int i=0;i<MAX;i++)
{
lotto[i] = number[i];
}
*/
}
public void sortLotto()
{
Arrays.sort(lotto);
/*
int tmp=0;
for(int i=0;i<lotto.length-1;i++)
{
for(int j=i+1;j<lotto.length;j++)
{
if(lotto[i]>lotto[j])
{
tmp = lotto[i];
lotto[i] = lotto[j];
lotto[j] = tmp;
}
}
}
*/
}
public void printLotto()
{
System.out.println(Arrays.toString(lotto));
/*
for(int i=0;i<lotto.length;i++)
System.out.print(lotto[i] + " ");
System.out.println();
*/
}
}
class LottoMain2
{
public static void main(String[] args)
{
Lotto lotto = new Lotto();
for(int i=0;i<5;i++)
lotto.execute();
}
}
1차원 배열에서 했던 클래스들 재사용
import java.util.Arrays;
import java.util.Random;
class Lotto
{
private int[][] lotto;
private Random random;
private final int MAX = 6;
private int numOfLotto;
Lotto(int numOfLotto)//로또를 몇세트를 만들것인지
{
this.numOfLotto = numOfLotto;
lotto = new int[numOfLotto][MAX];//5행 6열의 2차원 배열 생성
random = new Random();
}
public void execute()
{
makeLottos();
sortLottos();
printLottos();
}
public void makeLottos()
{
for(int i=0;i<numOfLotto;i++)
{
makeLotto(lotto[i]);
}
}
public void sortLottos()
{
for(int i=0;i<numOfLotto;i++)
{
sortLotto(lotto[i]);
}
}
public void printLottos()
{
for(int i=0;i<numOfLotto;i++)
{
printLotto(lotto[i]);
}
}
public boolean chkNum(int idx, int[] lotto)
{
for(int i=0;i<idx;i++)
{
if(lotto[idx]==lotto[i])
{
return false;
}
}
return true;
}
public void makeLotto(int[] lotto)
{
for(int i=0;i<lotto.length;i++)
{
lotto[i] = random.nextInt(45)+1;
if( !chkNum(i, lotto) )
{
i--;
}
}
}
public void sortLotto(int[] lotto)
{
Arrays.sort(lotto);
/*
int tmp=0;
for(int i=0;i<lotto.length-1;i++)
{
for(int j=i+1;j<lotto.length;j++)
{
if(lotto[i]>lotto[j])
{
tmp = lotto[i];
lotto[i] = lotto[j];
lotto[j] = tmp;
}
}
}
*/
}
public void printLotto(int[] lotto)
{
System.out.println(Arrays.toString(lotto));
/*
for(int i=0;i<lotto.length;i++)
System.out.print(lotto[i] + " ");
System.out.println();
*/
}
}
class LottoMain4
{
public static void main(String[] args)
{
Lotto lotto = new Lotto(5);
lotto.execute();
}
}
원하는 부분만 복사할 수 있다는 점과 인스턴스 생성을 방지하여 메모리 자원 낭비를 예방하고, 더 빠르게 실행된다. 가독성 측면에서 효율적
예시
자 공격하세요.
1234
숫자는 100이상 999 이하의 겹치지 않는 숫자여야 합니다.
자 공격하세요.
23
숫자는 100이상 999 이하의 겹치지 않는 숫자여야 합니다.
자 공격하세요.
123
0 스트라잌 1 볼
자 공격하세요.
111
숫자는 100이상 999 이하의 겹치지 않는 숫자여야 합니다.
자 공격하세요.
873
1 스트라잌 2 볼
자 공격하세요.
837
홈런
게임을 종료합니다.
package com.test.memo;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class UserComputerInput{
public static Scanner sc = new Scanner(System.in);
Random ran = new Random();
private int userInput;
private int[] user = new int[3];
private int[] com = new int[3];
public int[] getCom() {
return com;
}
public void printUser() {//사용자에게 보여주고 값을 사용자의 값이 틀리면 오류메시지를 보여주는 메서드
BaseBallGame game = new BaseBallGame(user, com);
boolean isUserInput = true;
inputComputerNum();//컴퓨터 난수 생성 후 사용자에게 입력값 받기
System.out.println("숫자 야구 게임을 시작합니다.");
while(!game.isGameOver()) {//종료되면 종료
System.out.print("유추할 세자리 숫자를 입력해주세요 : ");
isUserInput = inputUserVerific();
if(isUserInput) {
System.out.println("숫자는 100이상 999이하의 겹치지 않는 숫자여야 합니다.");
System.out.println("다시 입력하세요.");
}else {
game.playGameResult();
}
}
}
public void inputComputerNum() {//컴퓨터 값을 난수로 생성해주는 메서드
int comNum = ran.nextInt(999-100+1)+100; //100이상 999이하로 난수 생성
for(int i = 2; i >= 0; i--) {//배열에 숫자 넣고
com[i] = comNum %10;
comNum /= 10;
}
while(!inputComputerVerific(com)) {
comNum = ran.nextInt(999-100+1)+100;
for (int i = 2; i >= 0; i--) {
com[i] = comNum % 10;
comNum /= 10;
}
}
}
public boolean inputComputerVerific(int[] arr) {//컴퓨터 중복검사 메서드
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
if(arr[i] == arr[j]) {
return false;
}
}
}
return true;//중복이 없으면
}
public boolean inputUserVerific() {//사용자의 입력을 검증하는 메서드
userInput = sc.nextInt();
sc.nextLine();//엔터값 삭제
if(100 <= userInput && userInput <= 999) {//사용자 값이 100보다 크고 999보다작으면
for(int i = 2; i >= 0; i--) {//배열에 숫자 넣고
user[i] = userInput %10;
userInput /= 10;
}
for(int i = 0; i < 2; i++) {
for(int j = 2; j > i; j--) {//만약 그 전 배열이랑 숫자가 같으면 리턴해서 입력하고 , 같지 않으면 true
if(user[i] == user[j]) {
return true;
}
}
}return false;
}else { return true;
}
}
}
class BaseBallGame {
private int[] user;
private int[] com;
public BaseBallGame(int[] user, int[] com) {//UserComputerInput에 있는 배열을 이곳 생성자로
this.user = user;
this.com = com;
}
public void playGameResult(){
int strike = 0;
int ball = 0;
for(int i = 0; i < user.length; i++) {
if(user[i] == com[i]) {
strike++;
}
else {
ball += findBall(user[i], com);//ball리턴받아오기 > user[i]와 com배열 전체 비교
} //반환한 1이나 0을 더해서 출력
}
System.out.println("Strike: " + strike + ", Ball: " + ball);
}
public int findBall(int user, int[] com) {
for(int j = 0; j < com.length; j++) {
if(user == com[j]) {
return 1;
}
}
return 0;
}
public boolean isGameOver() {
return Arrays.equals(user, com);//두 값이 같으면 true리턴 아니면 flase리턴
}
}
public class Practice {
public static void main(String[] args) {
Scanner sc = UserComputerInput.sc;
UserComputerInput game = new UserComputerInput();
game.printUser();
}
}
package com.test.memo;
import java.util.Random;
import java.util.Scanner;
class Baseball {
private final int MAX;
private int[] baseBall;
private int[] attBaseBall;
private Random rnd;
public final int START_NUM;
public final int END_NUM;
private int bCnt;
private int sCnt;
public Baseball(int numberOfDigits) {// 몇자리 수로 게임할건지 사용자에게 입력받아서
MAX = numberOfDigits;
baseBall = new int[MAX];
attBaseBall = new int[MAX];
rnd = new Random();
START_NUM = setStartRange();// 자리 수에 따라 자릿수 정해지는 메서드
END_NUM = START_NUM * 10 - 1;// 위에서 한자리수 더한값에 -1
makeRNum(baseBall);
printArr(); // 디버깅 용도
}
private int setStartRange() {
int num = 1;
for (int i = 0; i < MAX - 1; i++)// 게임할 자릿수 지정하는 부분 2자리라고 입력되면 10이 한번만 곱해져서 10, 3자리면 2번 곱해져서 100
num *= 10;
return num;
}
private boolean numRange(int num)// 적합한 범위에 있는지를 확인하는
{
if (num < START_NUM || num > END_NUM)
return false;
else
return true;
}
private void makeRNum(int[] arrNum) {
while (true) {
int rNum = rnd.nextInt(END_NUM - START_NUM + 1) + START_NUM;// 발생되는 난수 범위가 100이상 999 > 3자리 입력받았다고 치면
mkArr(arrNum, rNum);
if (chkNumArr(arrNum))
break;// 참이되어야 break; 거짓이면 다시 while문 반복
}
}
private void mkArr(int[] arrNum, int num)// 자릿수에 상관없이 일반화시키기 위해서 divisor생성
{// 외부에서 호출할 일이 없어서 private으로 줬다.
int divisor = 1;
for (int i = 0; i < arrNum.length - 1; i++)// 3자리수니까 arr.Num.length는 현재 3
divisor *= 10;
for (int i = 0; i < arrNum.length; i++) {
arrNum[i] = num / divisor;// arrNum배열에 1,2,2 로 입력된다.
num %= divisor;
divisor /= 10;
}
}
private boolean chkNumArr(int[] arrNum)// 한 배열에 동일한 숫자는 없는지
{
for (int i = 0; i < arrNum.length - 1; i++)// i=0
{
for (int j = i + 1; j < arrNum.length; j++)// j=1 >이렇게 다르게 지정해주면서
{
if (arrNum[i] == arrNum[j])// if문에서 서로 배열을 비교
return false;
}
}
return true;
}
private void printArr() {
for (int i = 0; i < baseBall.length; i++)
System.out.print(baseBall[i]);
System.out.println();
}
public boolean setINum(int num) {
boolean result = true;
if (numRange(num)) {
mkArr(attBaseBall, num);
result = chkNumArr(attBaseBall);
} else
result = false;
return result;
}
public void playGame() {
int sCnt = 0;
int bCnt = 0;
for (int i = 0; i < baseBall.length; i++) {
for (int j = 0; j < attBaseBall.length; j++) {
if (baseBall[i] == attBaseBall[j])// 같은 숫자가 있으면
{
if (i == j)
sCnt++;// 같은 숫자가 있는데 해당 자리수도 같다면 strike ++
else
bCnt++;// 아니면 ball++
// break;로 쓰는게 나음 > 여기서는 전부 돌리는 중
}
}
}
this.sCnt = sCnt;
this.bCnt = bCnt;
}
public boolean showResult() {
boolean result = false;
if (sCnt == MAX) {
System.out.println("홈런");
result = true;
} else if (sCnt == 0 && bCnt == 0)
System.out.println("아웃");
else
System.out.println(sCnt + " 스트라잌 " + bCnt + " 볼");
return result;
}
}
class BaseballGame {
private Baseball computer;
public BaseballGame(int numberOfDigits) {
this.computer = new Baseball(numberOfDigits);
}
private boolean attack(int num) {
return computer.setINum(num);
}
public boolean playBaseballGame(int num)// 메인에서 사용자에게 값을 입력받아서
{
boolean result = false;
if (attack(num)) {
computer.playGame();
result = computer.showResult();
} else
System.out.println("숫자는 " + computer.START_NUM + "이상 " + computer.END_NUM + " 이하의 겹치지 않는 숫자여야 합니다.");
return result;// flase반환
}
}
public class Practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberOfDigits = 0;
int iNum = 0;
System.out.println("숫자 야구 게임을 시작합니다.");
while (true) {
System.out.println("원하는 자리수를 선택하세요.");
System.out.println("1~9까지 선택가능");
numberOfDigits = sc.nextInt();
if (numberOfDigits >= 1 && numberOfDigits <= 9)
break;
System.out.println("잘못 입력하셨습니다.");
}
BaseballGame bbGame = new BaseballGame(numberOfDigits);
while (true) {
boolean result;
System.out.println("자 공격하세요.");
iNum = sc.nextInt();
result = bbGame.playBaseballGame(iNum);
if (result) {
System.out.println("게임을 종료합니다.");
break;
}
}
sc.close();
}
}