[Java] Applied Random and Arrays
Random applications and examples - Creating a rock-paper-scissors game
Random rd = new Random(); By creating a random object, you can write output values according to the number of each case using if and else if statements. If it is not a number, create a NumberformatException, and if a number other than the menu is entered, write code so that it can be re-entered.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
if (userNum!@@T6 0@@=4) { If //1~3 is rolled
int pcNum = rnd.nextInt(3-@@T7 8@@1+1)+1;
//If the user wins
if((pcNum==1@ @T110@@&&userNum=@@T 122@@=2) || (pcNum==2&@@ T147@@&userNum==@@T 159@@3) || (pcNum@@T 171@@==3&&@@ T184@@userNum==1)) {
msg = ">>> You win!!\n";
}
//pc가 이긴 경우
else if(pcNum=@@T221@ @=2&&userNum=@@ T234@@=1) |@@T 247@@| (pcNum==3@@T259@ @&&userNum==@@ T272@@2) |@@T2 66@@| (pcNum@|) 4@@==1& &userNum==3))){
msg = ">>> pc won!!\n";
}
//If the user and the PC tie
else msg = ">>> It's a draw!!\n";
}
|
cs |
Array
It is the same type. An array is also an object.
How to declare an array int[] subjectArr4 = {@@T3 76@@100,90,@@T385 @@95,70,60@@T394@ @,100,98}; It is common to directly substitute data values into. When declaring an array, you can select the size of the array through object declaration as shown below, and then assign data values to each index value one by one.
Array name.length is an int value indicating the length (size) of the array. When you want to check the contents of an array index by index, you can use it as the basis of a conditional expression in a for statement.
|
1
2
3
4
5
6
7
8
|
int[] subjectArr;
subjectArr = new int[7];
int[] subjectArr2 =@@T4 66@@ new int[7];
int[] subjectArr3 @@T481@ @= new int[] {100@ @T488@@,90,95,70,@ @T495@@60,100,98};
int[] subjectArr4 = {100,90@@T 514@@,95,70,60,100,98};
|
cs |
Application Example 1 - Assigning a membership object to an array
Use the static method to check the conditions of the entered password. A static method is a method to which static, an access controller that can be used in other packages, has been applied. If the condition is met, the entered password is substituted into the variable as true. Otherwise, a warning message is written and the password can be entered again.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
package my.day09.a.array;
import java.util.Scanner;
import my.util.MyUtil;
public class MemberMain3 {
public static void main(String[] args) {
Member2[] mbrArr = new Member2[3];
/*
for(int i=0; i
System.out.println(mbrArr[i]);
}
null
null
null
*/
Scanner sc = new Scanner(System.in);
System.out.println(">>> 회원가입");
int menuNo = 0;
do {
System.out.println("\n=========== >> 메뉴 << ==========");
System.out.@@T913@ @println("1. Sign up 2. Check all members 3. End program");
|
try {
… menuNo = Integer.parseInt(sc.nextLine());
T947@@1<= menuNo && menuNo @@T964 @@<=3)) {
System.out .println(">> The number is not in the menu \n");
continue;
}
switch (menuNo) {
|
System.out@@T10 18@@.print("\n1. ID: ");
mbr.id = sc.nextLine();
boolean bool @@T10 35@@= false;
do {
System.out@@ T1050@@.print("2. Password : ");
… bool = MyUtil.isCheckPasswd(passwd);
if(bool) {
mbr.passwd = passwd;
{
System.out.println (">> Password must be entered as an 8-15 digit integer and must contain a mixture of upper and lower case letters, numbers and special characters!!\n");
| 03@@==true));
System.out@@T 1120@@.print("3. Name : ");
mbr.name = sc.nextLine();
for (int@@T1138@ @ i=0; i@@ T1146@@<mbrArr.length; i@@T1 152@@++) {
if (mbrArr[i] @ @T1164@@@@T1 165@@== null) {
mbrArr[i] @@T1177@ @= mbr; //Must be assigned to the index once. It should not keep changing to a new value.
break;
}
}
break;
case 2: //모든회원조회
int nullCount = 0;
for(int i=0; i<mbrArr.length; i++) {
if(mbrArr[i]!=null) { //null 여부 꼭 확인하기
System.out.println(mbrArr[i].showInfo());
} else nullCount++;
}
if(nullCount==mbrArr.length)
System.out.println("\n가입된 회원이 0명 입니다.");
break;
default:
break;
}
} catch (NumberFormatException e) {
System.out.println(">> 정수만 입력하세요! <<\n");
}
} while (!(menuNo==3));
sc.close();
System.out.println(">> 프로그램 종료 <<");
}
}
|
cs |
응용예제2 - 문자열 내 공백제거하기
문자열 내 공백을 제거하기 위해서는 문자열을 받은 배열과 공백을 제거한 문자열을 입력받을 배열을 생성해야 한다.
문자열 변수명.toCharArray(); 는 char 배열로 만들어 대입하는데 사용된다. 그리고 문자가 없이 ' '으로 초기화 되어 있는 공백수를 세서 새로운 배열 크기를 설정할 수 있다.
배열2=배열1 값을 대입해 줄 때, 만약 공백이라면 배열2의 인덱스 변수는 j--; 와 같이 공백 없이 입력될 수 있도록 해야 한다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package my.day09.b.array;
public class SpaceDeleteMain1 {
public static void main(String[] args) {
String str = " korea seou l 쌍용 강북 교육센터 ";
char[] chArr = str.toCharArray();
int len = 0;
for (int i=0; i<chArr.length; i++) {
if(chArr[i]!=' ') {
len++;
}
}
char[] resultchArr = new char[len];
for(int i=0, j=0; i<chArr.length; i++, j++) {
if(chArr[i] !=' ') {
resultchArr[j] = chArr[i];
} else j--;
}
System.out.println(String.valueOf(resultchArr));
}
}
|
cs |
응용예제3 - 로또 숫자 출력하기
전체 숫자에서 로또 당첨 숫자를 출력하는 코드를 만들기. 전체 숫자와 당첨숫자를 각각 배열로 생성해야 한다. 이 때, 주의해야 할 점은 입력된 당첨숫자가 겹치면 안되기 때문에 난수가 배열에 있는지 확인해야 한다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package my.day09.b.array;
import java.util.Random;
public class LottoMain2 {
public static void main(String[] args) {
int[] ballArr = new int[45];
int[] tempArr = new int[5]; //기존에 뽑았던 방번호를 기억시켜주는 저장소가 필요
for (int i=0; i<ballArr.length; i++) {
ballArr[i] = i+1; //배열의 방마다 데이터값 입력하기
//데이터값은 1~45
}
for (int i=0; i<tempArr.length; i++) {
tempArr[i] = -1;
}
Random rnd = new Random();
String result = "";
front:
for (int i=0; i<6; i++) {
int idx = rnd.nextInt(45);
for (int j=0; j<tempArr.length; j++) {
if(idx == tempArr[j]) {
i--;
continue front; //난수를 발생시켜주는 바깥 for문으로 가야한다.
}
}
if(i<5) {
tempArr[i] = idx;
}
String comma = (i<5)?",":"";
result += ballArr[idx]+comma;
}//end of for -----------------------------
System.out.println("\n로또 1등 당첨번호 : "+result);
}
}
|
cs |
Comments
No comments yet. Be the first!
164 posts in 테크
- 2233D Gaussian Splatting vs Unreal Engine: Two Ways to Build a 3D World — and Where Each One Ships
- 222LLMs Inside Unreal Engine: The New Skills Game Developers Need in 2026
- 220Living With Claude Fable 5: How the Most Capable Model Changes the Way You Actually Work
- 219Luma's Bet: From Video Generator to a Single Model That Thinks in Pixels
- 215The Best AI Video Models in 2026: Types, Differences, and Where This Is All Going