Java

자바 실습, 반복문, 배열, 별찍기,좌석예약

amungstudy 2023. 4. 24. 16:13

Basic Java Practice 1.hwp
0.20MB
Basic Java practice_2.hwp
0.21MB

 

 

 

디버깅모드 : 반복문에 브레이크 포인트 잡고 f11로 실행해서 f8로 다음다음 누르기 (디버그)

 


java practice 1

 

 

import java.util.Scanner;

 

public class Test1 {

/**

* 결과 : 3의 배수일 시 (입력받은 값은(는) 3의 배수입니다.)

: 3의 배수가 아닐 시 (입력받은 값은(는) 3의 배수가 아닙니다.)

*

*/

public static void main(String[] args) {

//import

Scanner sc = new Scanner(System.in);

while(true) {

System.out.println("정수를 입력해주세요 : ");

// 사용자가 입력한 값이 정수면 true, 정수 타입이 아니면 false

boolean isInteger = sc.hasNextInt();

if(!isInteger) {

System.out.println("정수가 아닙니다.");

sc.next(); // has쓸때는 continue 위에 빼줘야 정상작동함.

continue;

}

int num = sc.nextInt();

if(num <=0) {

System.out.println("종료합니다.");

break;

}

if(num %3 == 0) {

System.out.println(num+"은(는) 3의 배수입니다.");

}else {

System.out.println(num+"은(는) 3의 배수가 아닙니다.");

}

 

}

}

 

}


import java.util.Scanner;

 

public class Test2 {

 

public static void main(String[] args) {

/*

* 남성 또는 남 입력 시(남자 화장실은 왼쪽입니다.)

: 여성 또는 여 입력 시(여자 화장실은 오른쪽입니다.)

: 제시된 단어가 아닐 시(화장실을 찾을 수 없습니다.)

*

*/

Scanner sc = new Scanner(System.in);

System.out.println("성별을 입력해 주세요.(남성 또는 남 그리고 여성 또는 여)");

String s = sc.next();

//문자열 비교 시 equals 써야 한다.

if(s.equals("남성") || s.equals("남")) {

System.out.println("남자 화장실은 왼쪽 입니다.");

}else if(s.equals("여성") || s.equals("여")) {

System.out.println("여자 화장실은 오른쪽 입니다.");

}else {

System.out.println("화장실을 찾을 수 없습니다.");

}

 

//switch는 동등 비교 연산을 equals로 수행함

switch(s) {

case "남성" : case "남":

System.out.println("남자 화장실은 오른쪽입니다.");

break;

case "여성" : case "여":

System.out.println("여자 화장실은 왼쪽입니다.");

break;

default:

System.out.println("화장실을 찾을 수 없습니다.");

}

 

}

 

}


import java.util.Scanner;

 

public class Test3 {

 

public static void main(String[] args) {

// 임의로 지정된 1~ 100까지의 정수 맞추기

boolean isRun = true;

//임의의 정수

int guess = 78;

// 1~100까지의 난수

guess = (int)(Math.random() *100)+1 ;

//추측횟수

int count=0;

 

Scanner sc = new Scanner(System.in);

do {

System.out.println("1~100까지의 정수를 입력해주세요.");

int input = sc.nextInt();

String result = "성공입니다.";

if(input == guess) {

isRun = false;

 

}else if(input < guess) {

result = "낮습니다.";

}else {

result = "높습니다.";

}

count++;

System.out.println(result+" 추측횟수 : "+count);

}while(isRun);

 

}

 

}


import java.util.Scanner;

 

public class Test4 {

 

public static void main(String[] args) {

for(int i=0; i<5; i++) {

for(int j=0;j<5;j++) {

System.out.print("*");

}

System.out.println();

}

 

System.out.println("============================");

for(int i = 0; i<5; i++) {

for(int j=0;j<=i;j++) {

System.out.print("*");

}

System.out.println();

}

 

for(int i = 5; i>1; i--) {

for(int j = 1; j<i;j++) {

System.out.print("*");

}

System.out.println();

}

System.out.println("============================");

// 사용자에게 최대 가로 길이를 입력받아 삼각형 그리기

Scanner sc = new Scanner(System.in);

System.out.println("가로길이를 입력해주세요.");

int size = sc.nextInt();

/*

size : 4

[1]

[1][2]

[1][2][3]

[1][2][3][4]

-------------------

[1][2][3]

[1][2]

[1]

*/

/*

size : 5

[1]

[1][2]

[1][2][3]

[1][2][3][4]

[1][2][3][4][5]

-------------------

[1][2][3][4]

[1][2][3]

[1][2]

[1]

*/

 

//전체 라인 개수

int max = size * 2 - 1;

for(int i = 0; i<max;i++) {

// size : 5

// max : 9

// i : 0~8

// i < 5

if(i<size) {

// i: 0~4

//i가 size보다 작을때는 별의 출력 개수 증가

for(int j = 0; j<=i; j++) {

System.out.print("*");

}

}else {

// i : 5~8

// i가 size와 같거나 커지면 별의 출력 개수 감소

for(int j=1; j<=max-i; j++) {

System.out.print("*");

}

}

System.out.println();

}

System.out.println("============================");

 

//for문 두개로 그리기

int count = 1;

for(int i = 1; i<=max; i++) {

for(int j=0; j< count; j++) {

System.out.print("*");

}

if(i < size) {

count ++;

}else {

count --;

}

System.out.println();

}

 

 

 

}

 

}

 

 

 


import java.util.Scanner;

 

public class Test4_1 {

 

public static void main(String[] args) {

//라인 개수를 입력받아 최대치로 설정하고 공백을 활용하여 *을 그리자

//라인 개수 : 5

//[ ][ ][ ][ ][*]

//[ ][ ][ ][*][*][*]

//[ ][ ][*][*][*][*][*]

//[ ][*][*][*][*][*][*][*]

//[*][*][*][*][*][*][*][*][*]

//[ ][*][*][*][*][*][*][*]

//[ ][ ][*][*][*][*][*]

//[ ][ ][ ][*][*][*]

//[ ][ ][ ][ ][*]

Scanner sc = new Scanner(System.in);

System.out.println("라인 개수를 입력해주세요.");

int size = sc.nextInt();

int max = size *2-1;

//size = 5

//max = 9

for(int i = 1; i<=max; i++) {

if(i <= size) {

// i : 1 ~ 5

// size - i : 5- 1 == 4

// 5-2 == 3

// 5-3 == 2

// 5-4 == 1

// 5-5 == 0

 

//공백찍기

for(int j = size - i; j > 0; j--) {

System.out.print(" ");

}

// i : 1~5

// i * 2 - 1 : 그려줄 별의 개수

for(int j = i*2-1;j>0;j--) {

System.out.print("*");

}

 

}else {

 

// i값 6 7 8 9

// 별의 개수 7 5 3 1

// max :9

// (max-i) * 2 + 1 == 감소하는 별의 개수

// 공백 1 2 3 4

// i- size = 공백수

for(int j = 0; j<i-size; j++) {

System.out.print(" ");

}

for(int j = (max-i)*2+1;j>0;j--) {

System.out.print("*");

}

 

}

System.out.println();

}//end for

System.out.println("==================================");

for(int i =1, count = 0;i<=max; i++) {

if(i<=size) {

++count;

}else {

--count;

}

for(int j=1;j<=size-count; j++) {

System.out.print(" ");

}

for(int j = 1; j <= (count*2-1);j++) {

System.out.print("*");

 

}

System.out.println();

}

 

 

}//end main

 

}//end class

 


java practice 2

 

import java.util.Scanner;

 

public class Test1 {

 

public static void main(String[] args) {

// 5개의 정수(점수)를 입력받아 배열에 저장하고

// 배열에 저장된 점수의 평균을 구하시오.

int scores[] = new int[5];

Scanner sc = new Scanner(System.in);

int total = 0;

for(int i = 0; i<scores.length; i++) {

System.out.println("성적을 입력하세요 > ");

total += scores[i] = sc.nextInt();

}

System.out.println("총점은 : "+total);

double avg = total/ (double)scores.length;

System.out.printf("평균 성적은 : %.1f입니다.",avg);

}

 

}


import java.util.Scanner;

 

public class Test2 {

 

public static void main(String[] args) {

int[] numbers = new int[10];

//1~10까지 배열 생성

for(int i=0; i < numbers.length; i++) {

numbers[i] = (i+1);

 

}

Scanner sc = new Scanner(System.in);

System.out.println("검색할 번호를 입력하세요 > ");

int num = sc.nextInt();

for(int i =0; i<numbers.length;i++) {

if(num == numbers[i]) {

System.out.printf("%d는 [%d] index에 있습니다.",num,i);

break;

}

}

}

 

}


public class Test3 {

 

public static void main(String[] args) {

int [] scores = {18,15,24,3,2,22,1,19,50,30};

int minimum = scores[0];

for(int i : scores) {

if(i < minimum) {

minimum = i;

}

}

System.out.println("최소값은 : "+ minimum);

 

}

 

}


 

import java.util.Scanner;

 

public class Test4 {

 

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("크기를 입력해 주세요.");

int num = sc.nextInt();

int[] array[] = new int[num+1][];

for(int i = 0; i<array.length;i++) {

array[i] = new int[i+1];

for(int j =0; j<array[i].length;j++) {

array[i][j]=j;

 

}

 

}

for(int[] i : array) {

for(int j :i) {

System.out.print(j+" ");

}

System.out.println();

}

 

 

}

 

}

 


import java.util.Scanner;

 

public class Test5 {

 

public static void main(String[] args) {

// final 붙으면 읽기전용. 값이 변경되는걸 막아줌.

// 한 번 값이 지정이 되면 값을 재할당 할 수 없는 읽기전용 변수가 됨.

final int size = 10;

//size = 100; (오류)

int[] seats = new int[size];

 

while(true) {

System.out.println("-----------------------");

//for문 실행문 하나인 경우 {} 생략 가능

for(int i=0; i<size; i++)

System.out.print(i+1 + " ");

System.out.println("\n-----------------------");

for(int i = 0; i <size; i++)

System.out.print(seats[i]+" ");

System.out.println("\n-----------------------");

System.out.print("원하시는 좌석번호를 입력하세요(종료는 -1): ");

Scanner scan = new Scanner(System.in);

int seat = scan.nextInt();//좌석입력

//여기까지가 문제에서 제시된 내용

// index [0][1][2][3][4][5][6][7][8][9]

// seats [0][0][0][0][0][0][0][0][0][0]

if(seat==-1) {

System.out.println("종료합니다.");

break;

}

// 사용자가 입력한 좌석 번호에 따라 예약 진행

if(seats[seat-1]==0){

seats[seat-1] = 1;

System.out.println("예약이 완료되었습니다.");

}else {

System.out.println("이미 예약이 완료된 자리입니다.");

}

}

}

 

}


import java.util.Scanner;

 

/**

* 좌석 예약 프로그램

*/

public class Test6 {

 

public static void main(String[] args) {

// 예약된 좌석 정보를 저장 할 배열

byte[] seats[] = new byte[10][10];

 

// seats[0][0] = 1;

Scanner sc = new Scanner(System.in);

// 반복문 탈출 flag

boolean isRun = true;

 

while(isRun) {

System.out.println(" [ SCREEN ]");

for(int i = 0; i < seats.length; i++) {

// System.out.println(seats[i]);

// 좌석 열번호 - 출력

if(i == 0){

for(int j = 1; j <= seats.length; j++) {

System.out.print("["+j+"]");

}

System.out.println(" [열]");

}

for(int j = 0; j < seats[i].length; j++) {

// System.out.print(seats[i][j]);

if(seats[i][j] == 0) {

// System.out.print("[□]");

System.out.print("["+((char)9633)+"]");

}else{

// System.out.print("[■]");

System.out.print("["+((char)9632)+"]");

}

}

System.out.println(" ["+(char)(i+65)+"행]");

} // end for - 좌석 표시 끝

System.out.println("예약하실 좌석의 행이름을 입력해 주세요. ");

String s = sc.next();

char inputRow = s.charAt(0);

//65(A)~74(J)

if(inputRow < 65 || inputRow > 74) {

System.out.println("선택할 수 없는 자리입니다.");

continue;

}

System.out.println("선택하신 행은 :" + inputRow + "입니다.");

// 열번호 입력 받기 1~10

System.out.println("예약하실 좌석의 열번호를 입력해주세요.");

int columnNum = sc.nextInt();

if(columnNum < 1 || columnNum > 10) {

System.out.println("선택할 수 없는 열번호입니다.");

continue;

}

System.out.printf("선택하신 좌석은 %s행 %d열입니다. %n",inputRow,columnNum);

//예약진행여부

System.out.println("예약을 완료하시겠습니까? y/n");

String selected = sc.next();

if(selected.equals("Y")||selected.equals("y")||selected.equals("ㅛ")) {

//예약진행

// index번호 추출

int row = inputRow - 65;

int column = columnNum - 1;

//이미 예약된 자리인지 확인

if(seats[row][column]!=0) {

System.out.println("예약이 완료된 좌석입니다.");

continue;

}

seats[row][column] = 1; // 해당 자리 예약

System.out.println("예약이 완료 되었습니다.");

}else {

// ㅛ Y y 가 아닐 경우

System.out.println("예약이 취소되었습니다.");

}

 

}// end while

} // end main

 

}