My footsteps
배열 본문
728x90
public class Continu {
public static void main(String[] args) {
// int [] score; //1.int형식의 배열 scroe를 선언(참조변수)
// score = new int[5]; //2.배열 생성(몇개 넣을건지)
int[] score = new int[5]; //배열의 선언과 생성을 한번에
score[3] = 5; //어느배열에 어떤값을 넣을건지
score[2] = 100;
System.out.println("score[3] = "+score[3]);
System.out.println("score[2] = "+score[2]);
int num = score[3]; //변수 num에 score배열값 넣고
System.out.println(num); //출력도 가능
}
}
배열 간단 출력
(Arrays.toString)
import java.util.Arrays;
public class Continu {
public static void main(String[] args) {
int[] iArr = {100,90,50,70,60}; //길이가 5인 배열iArr의 초기화
// for(int i = 0; i<iArr.length; i++) {
// System.out.println(iArr);
// } //이렇게 하면 배열의 주소가 나온다. 값이 안나옴
System.out.println(Arrays.toString(iArr)); //배열 간단하게 출력하는 방법
}
}
public class Continu {
public static void main(String[] args) {
//점수 평균(average)을 구하는 문제
int sum = 0;
float average = 0f; //플로트형태로 저장하려할때는 뒤에 꼭 f를 붙여줘야함. 더블은 안붙여도됨
int [] score = {100,90,80,70,60};
for(int i =0; i<score.length; i++) {
sum += score[i]; //sum에다가 배열score의 값을 다 저장한다.[i]는 배열의 넘버임[0],[1]..
}
average = sum/(float)score.length;
//평균 = 점수총합/score갯수=score.length(즉,5개) float 형변환 이유는 소수점까지 구하기 위해
System.out.println("총점"+sum);
System.out.println("평균"+average);
}
}
public class Sco {
public static void main(String[] args) {
//최댓값과 최솟값 구하는 문제
int[] scroe = {90,80,70,60,50,100};
//배열의 초기화 꼭!!!!!!!!!!!!!!!!!!!!!!!
//최댓값: 100 최솟값:50
//90[0],80[1],70[2],60[3],50[4],100[5]
int max = scroe[0];
int min = scroe[0];
//★★★배열의 첫번째 값으로 최댓값,최솟값을 초기화 한다.즉 둘다 score[0] = 90인상태★★★
for(int i=1; i<scroe.length; i++) {
//i=1; i<6 즉 1~5까지
//★★★ 배열의 두번째 요소[1]부터 읽기위해 i=1로함. 위에서 초기화를 첫번째값으로 햇으니.★★★
//즉, score[1] = 80인상태.
if(scroe[i]>max) {
//80[1]>90 = 거짓..70[2]>90거짓..참일때까지 실행되고 참이면 값이 max에 저장.
max = scroe[i];
} else if(scroe[i] < min) {
//if문이 참이면 구문이 종료되고 else if문으로 넘어옴.
//80[1]<50 = 거짓..이런식으로 똑같이 최솟값을 찾으며 반복. 찾으면, 그 값이 min에 저장.
min = scroe[i];
}
}//for문 끝
System.out.println("최댓값"+max);
System.out.println("최솟값"+min);
}
}
import java.util.Arrays;
public class Sco {
public static void main(String[] args) {
//로또번호 섞기 문제
int[] numArr = {0,1,2,3,4,5,6,7,8,9};
//numArr 배열의 초기화
for(int i=0; i<numArr.length; i++) {
int n = (int)(Math.random()*10); //numArr길이만큼(10) 섞는다
int tmp = numArr[0];
numArr[0] = numArr[n];
numArr[n] = tmp;
//컵세개로 내용물 섞기
//numArr[n]의 의미는,[]안에는 배열의 순서를 나타내는거라서 저기에 [3]을 넣으면 numArr[3] 배열이
//랜덤으로 바뀌는 것이다.따라서 numArr[3] = 2다. 2가 랜덤으로 바뀌는것. 다만 그렇게 하고싶다면
//int n도 int 3 으로 다바꿔줘야만 정상 실행이 가능하다.
//여기서는 굳이 몇번째 배열을 지정하지않고 전체적으로 섞기 위해 numArr[n]을 사용한듯 하다
}//for문 종료
System.out.println(Arrays.toString(numArr));
//예제엔 for문을 넣었지만 for문을 삭제해도 정상적으로 돌아간다.
}
}
public class Sco {
public static void main(String[] args) {
//로또 번호 만들기 문제
int[] ball = new int[45]; // index 범위 = 0~44
for(int i=0; i < ball.length; i++) // ball배열의 길이만큼 섞어준다
ball[i] = i+1; // 1~45. 인덱스 범위가 0~44인데 +1이니까 시작을 1부터 함.
int tmp = 0; //두 값을 바꾸는데 사용할 임시변수(얜 걍 i와j를 바꾸기위한 수단임)
int j = 0; //임의의 값을 얻어서 저장할 변수
//섞어주는Zone.밑에 바꿔주는존 없이 출력하면 ball[0] = 1 이렇게 순차적으로 나옴
for(int i=0; i < 6; i++) { // 0~5개 요소까지 총6개만 바꾼다. 그래서 i<6
j = (int)(Math.random() * 45);
//index범위가 0~44 = 총 45개니까.0~44범위의 임의의 값을 얻는다.
//임의의 값을 j에 저장해놓기 위해 하는 작업
tmp = ball[i];
ball[i] = ball[j];
ball[j] = tmp;
// System.out.println(Arrays.toString(ball));
}
//바꿔주는Zone
// 배열 ball 앞에서부터 6개의 요소들을 출력. 앞의 6개부터 순차적으로 순서 바뀜
for(int i=0; i < 6; i++)
System.out.printf("ball[%d]=%d%n", i, ball[i]);
}
}
<4강> 연습문제
Q. 1부터 20까지의 정수 중에서 2또는 3의 배수가 아닌 수의 총합을 구하시오
public class Sco {
public static void main(String[] args) {
int sum = 0; //결과값을 출력할 변수 만들고
for(int i=1; i<= 20; i++) { //1부터 20까지
if(i%2!=0 && 1%3!=0) { //= 2 또는 3의 배수가 아닐때만
sum += i; //sum에 1을 더한다
}
}
System.out.println("sum"+sum);
}
}
public class Sco {
public static void main(String[] args) {
int sum = 0; //i의 값을 누적할 변수
int total = 0; //결과값을 반환할 변수
for(int i=1; i<= 10; i++) {
sum += i; //sum = sum+i 누적이니까, 2 = 1+1 / 3 = 2+1
total += sum; //total = total+sum
}
System.out.println("total"+total);
}
}
public class Sco {
public static void main(String[] args) {
int i = 0;
while(i <= 10) { //for(int i=0; i<=10;) 0~10
int j = 0;
while(j<=i) { //for(int j=0; j<=i;) 0~10
System.out.print("♥");
j++;
}
System.out.println();
i++;
}
}
}
//풀어서 쓰면 그냥
//while(i<=10) {
// System.out.print("♥");
// i++;
//}
//while(j<=i) {
// System.out.print("♥");
// j++;
//}
//두식다 똑같은건데 중첩해놓은것뿐임...
public class Sco {
public static void main(String[] args) {
int value = 0;
for(int i=1; i<=6; i++) {
value = (int)(Math.random()*6);
System.out.println(value);
}
}
}
답
컴퓨터가 정해놓은 답 맞추기 게임 만들기
//내가한거
import java.util.Scanner;
public class Sco {
public static void main(String[] args) {
int answer = 28;
int input = 0;
int count = 0;
Scanner s = new Scanner(System.in);
do {
count++;
System.out.print("1과 100사이의 값을 입력하세요 : ");
input = s.nextInt();
if(answer==input) {
System.out.println("정답입니다. 게임을 종료합니다");
}
if(input>answer) {
System.out.println("더 작은 수를 입력하세요");
}else if(input<answer) {
System.out.println("더 큰수를 입력하세요");
}else {
System.out.println("시도횟수는"+count+"입니다");
}
}while(input!=answer);
}
}
답
728x90
'예습 > code' 카테고리의 다른 글
While문,break문,continue문 (0) | 2023.01.15 |
---|---|
Math.random,for문 (0) | 2023.01.15 |
if 조건식,if-else문,else if,switch문 (0) | 2023.01.14 |
인터페이스 사용 이유 (0) | 2023.01.14 |
인터페이스의 다형성 (0) | 2023.01.14 |