1. [22.12.13] : 문제 1) 개수를 구하는 코드, 문제 2) 가장 큰 값, 문제 3) 그 위치를 출력
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test_221213_1_2 {
public static void main(String[] args) throws IOException {
/*
* res/data.txt 파일에 다음처럼 빈 공백으로 구분 된 값들이 있다.
*
* 20 30 29 39 49 38 10 19 87 29 38 27 8 90 87
*
* 문제 1 : 이 값들의 개수를 구하는 코드를 작성하시오.
* int count = 0; { // 코드를 작성하는 공간
*
*
* } Sysout.out.printf(“count is %d\n”, count);
*/
int count = 0;
{
FileInputStream fis = new FileInputStream("res/data.txt");
Scanner scan = new Scanner(fis);
// "20 30 29 39 49 38 10 19 87 29 38 27 8 90 87 "
while(scan.hasNext()) { // 정답
int temp = scan.nextInt();
count++;
}
fis.close();
}
System.out.printf("count is %d\n", count);
/*문제 2 : 이 값들 중에서 가장 큰 값이 무엇인지 출력하는 코드를 작성하시오.
int max = -1;
{
// 코드를 작성하는 공간
}
Sysout.out.printf(“max is %d\n”, max);*/
int max = -1;
{
FileInputStream fis = new FileInputStream("res/data.txt");
Scanner scan = new Scanner(fis); // "20 30 29 39 49 38 10 19 87 29 38 27 8 90 87 "
while(scan.hasNext()) {
int temp = scan.nextInt();
if(temp > max)
max = temp;
}
fis.close();
}
System.out.printf("max is %d\n", max);
/*문제 3 : 이 값들 중에 10 을 찾아서 그 위치(인덱스 값)을 출력하시오.
int index = -1;
{
// 코드를 작성하는 공간
}
System.out.printf(“index is %d\n”, index);*/
int index = -1;
{
FileInputStream fis = new FileInputStream("res/data.txt");
Scanner scan = new Scanner(fis); // "20 30 29 39 49 38 10 19 87 29 38 27 8 90 87 "
int i = 0;
while(scan.hasNext()) {
int temp = scan.nextInt();
index++; // i++;
if(temp == 10)
break; // index = i;
}
fis.close();
}
System.out.printf("index is %d\n", index);
}
}
2. [22.12.14] : 문제 4. 숫자의 자리 변경 방법
package day.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Random;
import java.util.Scanner;
public class test_221214_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
/*
* —----------------------------------------------------------------------------
* ---------------------------------- : 제어구조 + 배열
* —----------------------------------------------------------------------------
* ----------------------------------
*
* 문제 4 : 다음 각 절차를 따라 작성하시오.
*
* // 1. nums라는 이름으로 정수 15개를 저장할 수 있는 배열 객체를 생성한다. int nums =
*
* // 2. res/data.txt 파일에 저장된 값들을 nums 배열에 로드한다. { // 코드를 작성하는 공간
*
*
* System.out.println(“로드 완료”); }
*
* // 3. 0~14 범위의 랜덤값 2개를 얻어서 그 위치의 값을 서로 바꾼다. 그것을 50번 반복한다. { // 코드를 작성하는 공간
*
*
* System.out.println(“번호 섞기 완료”); }
*
* // 4. res/data-out.txt 파일로 배열의 값들을 저장 { // 코드를 작성하는 공간
*
*
*
* System.out.println(“저장 완료”); }
*/
int[] nums = new int[15];
{
FileInputStream fis = new FileInputStream("res/data.txt"); // (" ")이라는 파일과 연결된 FileInputStream을 "fis"라는 참조변수(연결 통로)로 만들어서 사용할 것이다.
Scanner scan = new Scanner(fis); // Scanner는 문자열을 통으로 받기 위해 사용하며, fis라는 연결통로에 scan이라는 버퍼를 만든다.
for(int i=0; i<15; i++)
nums[i]= scan.nextInt();
System.out.println("로드 완료");
fis.close(); // 닫아주는 것 주의!
}
{
Random rand = new Random();
for(int i=0; i<50; i++) { // random 난수의 반복 위치 생각(프로그래밍 동작 이해)
int s = rand.nextInt(15);
int d = rand.nextInt(15);
int temp = nums[s];
nums[s] = nums[d];
nums[d]= temp;
}
System.out.println("번호 섞기 완료");
}
{
FileOutputStream fos = new FileOutputStream("res/data-out.txt"); // (" ")이라는 파일 이름과 연결된 FileOutputStream을 "fos"라는 참조변수로 만들어서 사용할 것이다.
PrintStream out = new PrintStream(fos); // Scanner와 같이 PrintStream도 문자열을 통으로 받기 위해 사용하며, fos라는 연결통로에 out이라는 버퍼를 만든다.
// 스트림은 연결통로이고 버퍼는 임시 저장공간(박스)이다.
// FileOutputStream fos는 문자를, PrintStream out은 문자열을 사용
for(int i=0; i<15; i++) {
out.printf("%d", nums[i]);
if(i!=14)
out.print(",");
}
System.out.println("저장 완료"); // 20,30,29,39,49,38,10,19,87,29,38,27,8,90,87
fos.close(); // 닫아주는 것 주의!
}
}
}
3. 오목게임 수정[22.12.14]
package ex1.test;
import java.util.Scanner;
public class OmokTest3 {
public static void main(String[] args) {
// 오목에서 배열 10x10 100개 문자를 담을 수 있는 배열 이름: board
char[] board = new char[100];
char[][] board2 = new char[10][10];
//----------- board1 -------------------
for(int i=0; i<100; i++)
board[i] = '┼';
// board[15] ='○'; // 배열은 기존의 정수값과는 다르다.
// //board[44] ='○';
// board[(5-1)*10+(6-1)] ='○';
// for(int i=0; i<100; i++) {
//
// System.out.print(board[i]);
//
// if(i % 10 ==9)
// System.out.print("\n");
//
// }
//----------- board2 -------------------
for(int y=1; y<=10; y++) {
for(int x =1; x<=10; x++) {
board2[y-1][x-1] = '┼';
}
}
for(int y=1; y<=10; y++) {
for(int x =1; x<=10; x++) {
board2[0][x-1] = '┬';
board2[9][x-1] = '┴';
}
board2[y-1][0] = '├';
board2[y-1][9] = '┤';
board2[0][0] = '┌';
board2[0][9] = '┐';
board2[9][0] = '└';
board2[9][9] = '┘';
}
for(int y=1; y<=10; y++) {
for(int x =1; x<=10; x++) {
System.out.printf("%c", board2[y-1][x-1]);
}
System.out.print("\n");
}
//----------- omok game -------------------
Scanner scan = new Scanner(System.in); // while문의 조건 처리는 변수화하여 최대한 적게 해야한다.
int ox, oy;
for(int count =100; count>0; count--) { // 중첩이 최대한 적게 만들어야 한다.
System.out.println("(x, y) > ");
ox = scan.nextInt();
oy = scan.nextInt();
if(ox<1 || ox>10 || oy<1 || oy>10) { // 예외 처리 추가 (같은 위치에 오목돌 겹치지 않게 하기)
System.out.println("x는 1~10의 수만 입력할 수 있습니다. x: ");
System.out.println("y는 1~10의 수만 입력할 수 있습니다. y: ");
continue;
}
if(count % 2 == 0)
board2[ox-1][oy-1] = '○';
else
board2[ox-1][oy-1] = '●';
if(count<100) {
if(board2[ox-1][oy-1] == '○' || board2[ox-1][oy-1] == '●') {
System.out.println("돌이 있습니다. ");
continue;
}
}
for(int y=1; y<=10; y++) {
for(int x =1; x<=10; x++) {
System.out.printf("%c", board2[y-1][x-1]);
}
System.out.print("\n");
}
}
// //------------------------------------- --------------- --------------- ---------------
// <원래>
// if(count % 2 == 0)
// board2[ox-1][oy-1] = '○';
// else
// board2[ox-1][oy-1] = '●';
//
//
}
}
// 자리 배치하기
// 랜덤하게 섞어서 추가 조건 처리 : 누구랑 누구랑 묶여서?
// UI 이쁘게
4-1. [22.12.15] : 문제 5. 문자의 자리 변경 방법
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class test_221215_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
/*
* //문제 5 : 다음 각 절차를 따라 작성하시오.
*
*
* // 1. res/alphabet.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오. // abcdefghijklmn
*
* // 2. alphabet이라는 이름으로 문자 15개를 저장할 수 있는 배열 객체를 생성한다. [ ] alphabet = [ ];
*
* // 3. res/alphabet.txt 파일에 저장된 구분자가 없는 영문자 값들을 alphabet 배열에 로드한다. { // 코드를
* 작성하는 공간
*
*
* System.out.println(“로드 완료”); }
*
* // 3. 배열의 값이 다음과 같은 상태가 되도록 자리를 바꾼다. // nmlkjihgfedcba
*
* { // 코드를 작성하는 공간
*
*
*
* System.out.println(“자리변경 완료”); }
*
* // 4. res/alphabet-out.txt 파일로 배열의 값들을 저장 { // 코드를 작성하는 공간
*
*
*
* System.out.println(“저장 완료”); }
*/
// 1. res/alphabet.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오. // abcdefghijklmn
char[] alphabet = new char[15];
// 2. alphabet이라는 이름으로 문자 15개를 저장할 수 있는 배열 객체를 생성한다. [ ] alphabet = [ ];
{
FileInputStream fis = new FileInputStream("res/alphabet.txt");
Scanner scan = new Scanner(fis);
String line = scan.nextLine();
System.out.printf("%s\n",line);
for(int i = 0; i<14; i++) { // for-each 구문도 생각!!
alphabet[i] = line.charAt(i);
System.out.printf("%c",alphabet[i]);
}
System.out.println();
System.out.println("로드 완료");
}
// 3. 배열의 값이 다음과 같은 상태가 되도록 자리를 바꾼다. // nmlkjihgfedcba
{
char temp; // 다른 방식 :
for(int j=0; j<15-1; j++) { // 1. : 배열 교차,
// 2. 문자열 바꿔주는 방법 : fis.read는 문자열을 int로 반환, toCharArray라는 메서드 사용
for(int i=0; i<15-1-j; i++) {
if(alphabet[i+1]>alphabet[i]) { // "-1"은 배열이 i와 i+1이라서 이렇게 설계했다. 생각해보기(숫자 대입)
temp = alphabet[i]; // "-j"는 비교되는 값을 한곳으로 몰아 넣고 나머지를 다시 정렬한다.
alphabet[i] = alphabet[i+1];
alphabet[i+1] = temp;
}
}
}
for(int i=0; i<15-1; i++) {
System.out.printf("%c",alphabet[i]);
}
System.out.println("\n자리변경 완료");
}
// 4. res/alphabet-out.txt 파일로 배열의 값들을 저장 { // 코드를 작성하는 공간
{
FileOutputStream fos = new FileOutputStream("res/alphabet.txt");
PrintStream out = new PrintStream(fos);
for(int i=0; i<15; i++) {
out.printf("%c", alphabet[i]);
}
fos.close();
//fos.wr
System.out.println("\n저장 완료");
}
}
}
4-2. [22.12.15] : 2차원 배열 요소의 순서
- 1차원 배열을 2차원으로 확장할 때 선언 방법을 보시면 차원이 증가할 때마다 배열의 선언 뒤쪽에 붙이는 것이 아니라 앞으로 붙이는 형식으로 되어 있습니다. (메모리에 저장되는 구조를 볼 때)
char a[4]; // 4바이트 1차원 배열
char b[2][4]; // 위의 1차원 배열을 2개 붙여 2차원 배열 생성
char c[3][2][4]; // 위의 2차원 배열을 3개 붙여 3차원 배열 생성
- 즉, b[2][4]는 메모리에 저장되는 구조가 아래와 같이 나타납니다.
b[0][0] b[0][1] b[0][2] b[0][3] b[1][0] b[1][1] b[1][2] b[1][3]
- 1차원 배열로 변환했을 때 쉽게 알아볼 수 있으려면 위의 구조를 이해하고 있는 편이 나중에 배열 계산을 할 때 실수를 막는 방법이 될 겁니다.
4-3. [22.12.15] : 문제 6. 제어구조 중첩 + 다차원 배열
package com.newlecture;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
/*—--------------------------------------------------------------------------------------------------------------
: 제어구조 중첩 + 다차원 배열
—--------------------------------------------------------------------------------------------------------------
문제 6 : 다음 각 절차를 따라 작성하시오.
// 1. res/bitmap.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.
11111111110000000000
11111111100000000000
11111111000000000000
11111110000000000000
11111100000000000000
11111000000000000000
11110000000000000000
11100000000000000000
11000000000000000000
10000000000000000000
2. bitmap이라는 이름으로 20X10크기의 정수를 담을 수 있는 이차원 배열을 생성하시오.
[ ] bitmap = [ ];
3. 다음 그림과 같은 모양이 되도록 값의 위치를 변경하시오
00000000001111111111
00000000000111111111
00000000000011111111
00000000000001111111
00000000000000111111
00000000000000011111
00000000000000001111
00000000000000000111
00000000000000000011
00000000000000000001
{
// 코드를 작성하는 공간
System.out.println(“자리변경 완료”);
}
// 4. res/bitmap-out.txt 파일로 bitmap 배열의 값들을 저장
{
// 코드를 작성하는 공간
System.out.println(“저장 완료”);
}
*/
public class test_221215_1_2 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
int[][] bitmap = new int[10][20];
String[] nums = new String[10];
char[] num = new char[20];
{
FileInputStream fis = new FileInputStream("res/bitmap.txt");
Scanner scan = new Scanner(fis);
while(scan.hasNext()) {
for(int i=0; i<10; i++) {
nums[i] = scan.nextLine(); // 1. 문자열로 받기
System.out.printf("%s\n", nums[i]);
}
System.out.println("문자열로 받기");
System.out.println();
for(int j = 0; j<10; j++) {
for(int i=0; i<20; i++) {
// 2. 문자열을 문자로 변환.
num[i] = nums[j].charAt(i); // 1차원배열은 1차원배열로 받아야한다. 그리고 배열의 자리수 생각
System.out.printf("%c", num[i]);
bitmap[j][i] = num[i]*1; // 3. 문자열을 숫자로 변환
}
System.out.println();
}
System.out.println("문자로 변환한 것 출력");
}
System.out.println();
//System.out.println(bitmap[0][0]);
for(int k = 0; k<10; k++) {
for(int i=0; i<20; i++) {
System.out.printf("%c", bitmap[k][i]);
}
System.out.println();
}
System.out.println("숫자로 변환한 것 출력");
}
System.out.println();
{ // ****내가 부족한 부분 : 너무 막 생각했다. 동작 과정(흐름)을 생각해보기!!(어느 부분이 자리바꾸는지 생각!!)
// 에러 수정이 안된다면, 내가 자세히 안본 코드를 다시 보면서 동작 흐름을 생각해보면 된다!!
int temp;
for(int k = 0; k<10; k++){
for(int j=0; j<20-1; j++) { // 4. 문자를 숫자로 변환하여 역순으로 대입
for(int i=0; i<20-1-j; i++) {
if(bitmap[k][i+1]<bitmap[k][i]) { // "-1"은 배열이 i와 i+1이라서 이렇게 설계했다. 생각해보기(숫자 대입)
temp = bitmap[k][i]; // "-j"는 비교되는 값을 한곳으로 몰아 넣고 나머지를 다시 정렬한다.
bitmap[k][i] = bitmap[k][i+1];
bitmap[k][i+1] = temp;
}
}
}
}
for(int j = 0; j<10; j++) {
for(int i=0; i<20; i++) {
System.out.printf("%c", bitmap[j][i]);
}
System.out.println();
}
System.out.println("자리변경 완료");
}
// 5. 파일 저장하기
{
FileOutputStream fos = new FileOutputStream("res/bitmap-out.txt");
PrintStream out = new PrintStream(fos);
for(int j = 0; j<10; j++) {
for(int i=0; i<20; i++)
out.printf("%c", bitmap[j][i]);
if(j!=9)
out.print("\n");
}
fos.close();
}
}
}
5. [22.12.16] : 문제 8. 7번 문제를 함수를 이용하여 코드를 나누어 만들어보시오.
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test_221219_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
/*
* —---------------------------------------------------------
* -------------------- : 제어구조 중첩 + 다차원 배열 + 배열+함수 문제
* —-------------------------------------------
* ------------------ 문제 8 : 다음 각 절차를 따라 작성하시오.
*
* // 7번 문제를 함수를 이용하여 코드를 나누어 만들어보시오.
*/
// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
int[][] map = new int[3][5];
char[][] board = new char[6][10];
String[] nums = new String[5];
char[] num = new char[5];
changeMap(map, nums, num);
printChangeMap(map);
drawBoard(map, board);
printBoard(board);
}
static void changeMap(int[][] map, String[] nums, char[] num) throws FileNotFoundException {
// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
FileInputStream fis = new FileInputStream("res/map.txt");
Scanner scan = new Scanner(fis);
while(scan.hasNext()) {
for(int i=0; i<3; i++) {
nums[i] = scan.nextLine(); // 1. 문자열로 받기
System.out.printf("%s\n", nums[i]);
}
System.out.println("문자열로 받기\n");
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
// 2. 문자열을 문자로 변환.
num[i] = nums[j].charAt(i); // 1차원배열은 1차원배열로 받아야한다. 그리고 배열의 자리수 생각
System.out.printf("%c", num[i]);
map[j][i] = num[i]*1; // 3. 문자열을 숫자로 변환
}
System.out.println();
}
System.out.println("문자로 변환한 것 출력\n");
}
}
static void printChangeMap(int[][] map) {
for(int k = 0; k<3; k++) {
for(int i=0; i<5; i++) {
System.out.printf("%c", map[k][i]);
}
System.out.println();
}
System.out.println("map 데이터 로드 완료\n");
}
static void drawBoard(int[][] map, char[][] board) {
// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
// 1칸이 크기가 4배로 불려짐.(배수 이용)
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
int x=2*i;
int y=2*j;
if(map[j][i] == '0') {
board[y][x] = '┌';
board[y][x+1] = '┐';
board[y+1][x] = '└';
board[y+1][x+1] = '┘';
}
else if(map[j][i] == '1') {
board[y][x] = '▩';
board[y][x+1] = '▩';
board[y+1][x] = '▩';
board[y+1][x+1] = '▩';
}
}
}
System.out.println("board 그리기 완료\n");
}
static void printBoard(char[][] board) {
for(int n = 0; n<6; n++) {
for(int m=0; m<10; m++) {
System.out.printf("%c", board[n][m]);
}
System.out.println();
}
System.out.println("board 출력 완료\n");
}
}
6. [22.12.16] : 문제 7. 제어구조 중첩 + 다차원 배열 + 배열 문제(+자리 바꾸기)
package day.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/*—--------------------------------------------------------------------------------------------------------------
: 제어구조 중첩 + 다차원 배열 + 배열 문제
—--------------------------------------------------------------------------------------------------------------
문제 7 : 다음 각 절차를 따라 작성하시오.
// 1. res/map.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.
00010
01010
00000
// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
[ ] map = [ ];
[ ] board = [ ];
// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
{
// 코드를 작성하는 공간
System.out.println(“map 데이터 로드 완료”);
}
// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
// map에서 0은 다음 모양과 같다.
// ┌ ┐
// └ ┘
// map에서 1은 다음 모양과 같다.
// ▩▩
// ▩▩
// map에서 읽은 데이터를 이용해서 board 배열을 채우시오. 다음은 board 배열에 채워진
// 모습니다.
// ┌ ┐┌ ┐┌ ┐▩▩┌ ┐
// └ ┘└ ┘└ ┘▩▩└ ┘
// ┌ ┐▩▩┌ ┐▩▩┌ ┐
// └ ┘▩▩└ ┘▩▩└ ┘
// ┌ ┐┌ ┐┌ ┐┌ ┐┌ ┐
// └ ┘└ ┘└ ┘└ ┘└ ┘
{
// 코드를 작성하는 공간
System.out.println(“board 그리기 완료”);
}
// 5. board 배열을 화면에 출력하는 코드를 작성하시오.
{
// 코드를 작성하는 공간
System.out.println(“board 출력 완료”);
}
*/
public class test_221216_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
int[][] map = new int[3][5];
char[][] board = new char[6][10];
String[] nums = new String[5];
char[] num = new char[5];
// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
{
FileInputStream fis = new FileInputStream("res/map.txt");
Scanner scan = new Scanner(fis);
while(scan.hasNext()) {
for(int i=0; i<3; i++) {
nums[i] = scan.nextLine(); // 1. 문자열로 받기
System.out.printf("%s\n", nums[i]);
}
System.out.println("문자열로 받기\n");
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
// 2. 문자열을 문자로 변환.
num[i] = nums[j].charAt(i); // 1차원배열은 1차원배열로 받아야한다. 그리고 배열의 자리수 생각
System.out.printf("%c", num[i]);
map[j][i] = num[i]*1; // 3. 문자열을 숫자로 변환
}
System.out.println();
}
System.out.println("문자로 변환한 것 출력\n");
}
for(int k = 0; k<3; k++) {
for(int i=0; i<5; i++) {
System.out.printf("%c", map[k][i]);
}
System.out.println();
}
System.out.println("map 데이터 로드 완료\n");
}
// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
{
// 1칸이 크기가 4배로 불려짐.(배수 이용)
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
int x=2*i;
int y=2*j;
if(map[j][i] == '0') {
board[y][x] = '┌';
board[y][x+1] = '┐';
board[y+1][x] = '└';
board[y+1][x+1] = '┘';
}
else if(map[j][i] == '1') {
board[y][x] = '▩';
board[y][x+1] = '▩';
board[y+1][x] = '▩';
board[y+1][x+1] = '▩';
}
}
}
System.out.println("board 그리기 완료\n");
}
{
for(int n = 0; n<6; n++) {
for(int m=0; m<10; m++) {
System.out.printf("%c", board[n][m]);
}
System.out.println();
}
System.out.println("board 출력 완료\n");
}
}
}
7. [22.12.19] : 문제 8. 제어구조 중첩 + 다차원 배열 + 배열+함수 문제
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test_221219_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
/*
* —---------------------------------------------------------
* -------------------- : 제어구조 중첩 + 다차원 배열 + 배열+함수 문제
* —-------------------------------------------
* ------------------ 문제 8 : 다음 각 절차를 따라 작성하시오.
*
* // 7번 문제를 함수를 이용하여 코드를 나누어 만들어보시오.
*/
// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
int[][] map = new int[3][5];
char[][] board = new char[6][10];
String[] nums = new String[5];
char[] num = new char[5];
changeMap(map, nums, num);
printChangeMap(map);
drawBoard(map, board);
printBoard(board);
}
static void changeMap(int[][] map, String[] nums, char[] num) throws FileNotFoundException {
// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
FileInputStream fis = new FileInputStream("res/map.txt");
Scanner scan = new Scanner(fis);
while(scan.hasNext()) {
for(int i=0; i<3; i++) {
nums[i] = scan.nextLine(); // 1. 문자열로 받기
System.out.printf("%s\n", nums[i]);
}
System.out.println("문자열로 받기\n");
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
// 2. 문자열을 문자로 변환.
num[i] = nums[j].charAt(i); // 1차원배열은 1차원배열로 받아야한다. 그리고 배열의 자리수 생각
System.out.printf("%c", num[i]);
map[j][i] = num[i]*1; // 3. 문자열을 숫자로 변환
}
System.out.println();
}
System.out.println("문자로 변환한 것 출력\n");
}
}
static void printChangeMap(int[][] map) {
for(int k = 0; k<3; k++) {
for(int i=0; i<5; i++) {
System.out.printf("%c", map[k][i]);
}
System.out.println();
}
System.out.println("map 데이터 로드 완료\n");
}
static void drawBoard(int[][] map, char[][] board) {
// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
// 1칸이 크기가 4배로 불려짐.(배수 이용)
for(int j = 0; j<3; j++) {
for(int i=0; i<5; i++) {
int x=2*i;
int y=2*j;
if(map[j][i] == '0') {
board[y][x] = '┌';
board[y][x+1] = '┐';
board[y+1][x] = '└';
board[y+1][x+1] = '┘';
}
else if(map[j][i] == '1') {
board[y][x] = '▩';
board[y][x+1] = '▩';
board[y+1][x] = '▩';
board[y+1][x+1] = '▩';
}
}
}
System.out.println("board 그리기 완료\n");
}
static void printBoard(char[][] board) {
for(int n = 0; n<6; n++) {
for(int m=0; m<10; m++) {
System.out.printf("%c", board[n][m]);
}
System.out.println();
}
System.out.println("board 출력 완료\n");
}
}
8. [22.12.19] : 문제 9. 제어구조 중첩 + 수학 문제
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test_221219_1_2 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
// —--------------------------------------------------------------------------------------------------------------
// : 제어구조 중첩 + 수학 문제
// —--------------------------------------------------------------------------------------------------------------
//
// 문제 9 : 다음 각 절차를 따라 작성하시오.
//
// // 1. 다음 한문장을 반복해서 다음과 같은 출력이 가능하도록 하는 코드를 작성하시오.
// System.out.printf(“%c”, ‘┼’); 또는 System.out.printf(“%c”, ‘○’);
//
// ○┼┼┼┼┼┼┼┼┼
// ┼○┼┼┼┼┼┼┼┼
// ┼┼○┼┼┼┼┼┼┼
// ┼┼┼○┼┼┼┼┼┼
// ┼┼┼┼○┼┼┼┼┼
// ┼┼┼┼┼○┼┼┼┼
// ┼┼┼┼┼┼○┼┼┼
// ┼┼┼┼┼┼┼○┼┼
// ┼┼┼┼┼┼┼┼○┼
// ┼┼┼┼┼┼┼┼┼○
//
//
// // 2. 위의 답을 복사해서 다음과 같은 출력이 가능하도록 코드를 수정하시오.
// ○┼┼┼┼┼┼┼┼┼○
// ┼○┼┼┼┼┼┼┼○┼
// ┼┼○┼┼┼┼┼○┼┼
// ┼┼┼○┼┼┼○┼┼┼
// ┼┼┼┼○┼○┼┼┼┼
// ┼┼┼┼┼○┼┼┼┼┼
// ┼┼┼┼○┼○┼┼┼┼
// ┼┼┼○┼┼┼○┼┼┼
// ┼┼○┼┼┼┼┼○┼┼
// ┼○┼┼┼┼┼┼┼○┼
// ○┼┼┼┼┼┼┼┼┼○
//
//
// // 3. 위의 답을 복사해서 다음과 같은 출력이 가능하도록 코드를 수정하시오.
// ○┼┼┼┼┼┼┼┼┼○
// ┼○┼┼┼┼┼┼┼○┼
// ┼┼○┼┼┼┼┼○┼┼
// ┼┼┼○┼┼┼○┼┼┼
// ┼┼┼┼○┼○┼┼┼┼
// ┼┼┼┼┼○┼┼┼┼┼
// ┼┼┼┼○○○┼┼┼┼
// ┼┼┼○○○○○┼┼┼
// ┼┼○○○○○○○┼┼
// ┼○○○○○○○○○┼
// ○○○○○○○○○○○
//
{
for(int y = 0; y<10; y++) {
for(int x = 0; x<10; x++) {
if(y ==x) // 대각선에 '○'
System.out.printf("%c", '○');
else
System.out.printf("%c", '┼');
}
System.out.print("\n");
}
System.out.println("1번 과제 출력 완료\n");
}
{
for(int y = 0; y<11; y++) { // 0,0 / 1,1 / 2,2 / 3,3
for(int x = 0; x<11; x++) { // 9,0 / 8,1
if(y == x || y == 10-x) // 대각선에 '○'
System.out.printf("%c", '○');
else
System.out.printf("%c", '┼');
}
System.out.print("\n");
}
System.out.println("2번 과제 출력 완료\n");
}
{
for(int y = 0; y<11; y++) {
for(int x = 0; x<11; x++) {
if(y == x || y == 10-x || ( y< 10-x && y > x ))
System.out.printf("%c", '○');
else
System.out.printf("%c", '┼');
}
System.out.print("\n");
}
System.out.println("3번 과제 출력 완료");
}
}
}
9. [22.12.20] : 문제 10. canvas에 직선 그리기
[프로그램 제작 시]
- 개발 일지 제작 하기 : 개발 목적, 키워드, 어려웠던 부분, 다른 방법?, 개선 부분!!
package day.test;
import java.io.IOException;
public class test_221220_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
// 프로그램 제작 시, 생각할 부분 : 개발 목적, 키워드, 어려웠던 부분, 다른 방법?, 개선 부분!!
// 문제 10 : 다음 각 절차를 따라 작성하시오. 키워드 힌트가 필요하다면 열어보기!
// 1. canvas라는 이름으로 문자 20x20개를 저장할 수 있는 배열 객체를 생성한다.
// 2. canvas 배열을 다음처럼 ‘┼’ 문자로 채우는 코드를 작성하시오.
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// 3. ‘○’ 문자를 이용해서 canvas에 선을 그리는 함수를 작성하시오.
// 함수의 호출 예
// 위의 결과는 다음과 같다.
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼○┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼○┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼○┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼○┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼○┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼○┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼○┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼○┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼○┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼○┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼○┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
// ┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼
char[][] canvas = new char[20][20];
{
// 코드를 작성하는 공간
for (int j = 0; j < 20; j++) {
for (int i = 0; i < 20; i++) {
canvas[j][i] = '┼';
System.out.printf("%c", canvas[j][i]);
}
System.out.println();
}
System.out.println("board 초기화 완료\n");
}
{
// 2번 문제 코드
// 3번 문제풀이로 작성된 함수를 호출하는 코드
int x1 = 18;
int y1 = 3;
int x2 = 3;
int y2 = 18;
drawLineOnCanvas(canvas, x1, y1, x2, y2);
}
}
static void drawLineOnCanvas(char[][] canvas, int x1, int y1, int x2, int y2) {
int incline = (y2 - y1) / (x2 - x1);
for (int j = 0; j < 20; j++) {
for (int i = 0; i < 20; i++) {
canvas[j][i] = '┼';
if (x2 > x1 && y2 > y1) {
if ((j - y1) == incline * (i - x1) && i <= x2 - 1 && i >= x1 - 1 && j <= y2 - 1 && j >= y1 - 1)
canvas[j][i] = '○';
}
else if (x2 < x1 && y2 > y1) {
if ((j - y1) == incline * (i - x1) && (i >= x2 - 1 && i <= x1 - 1) && (j <= y2 - 1 && j >= y1 - 1))
canvas[j][i] = '○';
}
else if (x2 > x1 && y2 < y1) {
if ((j - y1) == incline * (i - x1) && (i <= x2 - 1 && i >= x1 - 1) && (j >= y2 - 1 && j <= y1 - 1))
canvas[j][i] = '○';
}
else if (x2 < x1 && y2 < y1) {
if ((j - y1) == incline * (i - x1) && (i >= x2 - 1 && i <= x1 - 1) && (j >= y2 - 1 && j <= y1 - 1))
canvas[j][i] = '○';
}
System.out.printf("%c", canvas[j][i]);
}
System.out.println();
}
}
}
10. [22.12.20] : 문제 11. 문제 10을 객체 지향 프로그래밍으로 설계
package day.test;
import java.io.IOException;
public class test_221220_1_2 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
//문제 11 : 10번 문제를 다음처럼 객체지향으로 구현하려고 한다. 각 문장에 올바른 답을 적으시오.
Canvas canvas = new Canvas();
canvas.drawLine(18,2,2,19);
}
}
package day.test;
public class Canvas{
// 1. Canvas 클래스를 생성하고 속성으로 char[][] buf를 추가하고 이 속성으로 참조할 이차원 배열 객체(20x20 크기)를
// 생성하는 생성자를 작성하시오.
private int x1;
private int y1;
private int x2;
private int y2;
private char[][] buf; // 초반엔, 배열 선언만
public Canvas() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
buf = new char[20][20]; // 생성자로 배열 초기화
}
public void drawLine(int x1, int y1, int x2, int y2) {
int incline = (y2 - y1) / (x2 - x1);
for (int j = 0; j < 20; j++) {
for (int i = 0; i < 20; i++) {
buf[j][i] = '┼';
if (x2 > x1 && y2 > y1) {
if ((j - y1) == incline * (i - x1) && i <= x2 - 1 && i >= x1 - 1 && j <= y2 - 1 && j >= y1 - 1)
buf[j][i] = '○';
}
else if (x2 < x1 && y2 > y1) {
if ((j - y1) == incline * (i - x1) && (i >= x2 - 1 && i <= x1 - 1) && (j <= y2 - 1 && j >= y1 - 1))
buf[j][i] = '○';
}
else if (x2 > x1 && y2 < y1) {
if ((j - y1) == incline * (i - x1) && (i <= x2 - 1 && i >= x1 - 1) && (j >= y2 - 1 && j <= y1 - 1))
buf[j][i] = '○';
}
else if (x2 < x1 && y2 < y1) {
if ((j - y1) == incline * (i - x1) && (i >= x2 - 1 && i <= x1 - 1) && (j >= y2 - 1 && j <= y1 - 1))
buf[j][i] = '○';
}
System.out.printf("%c", buf[j][i]);
}
System.out.println();
}
}
}
11. [22.12.20] : 문제 12. UML 이용한 객체 지향 프로그래밍 문제(클래스 관계 이용)
0) 들어가기전, 객체 배열 정리
-
항상, 새로 만들어진 객체에 배열을 사용하기 위해서 2단계의 과정을 무조건 진행해야한다.
-
1단계 : 배열 참조
Student[] students = new Student[10]; // 중요!! 배열 참조(나는 생성자에서 만드려고 했다.)
-
2단계 : 배열 할당
students[j] = new Student(); // 중요!! 배열 할당!!(내가 이해하지 못한 부분) // 그 만들어진 공간에 이름 붙여주는 역할
-
위와 같이 객체 배열 설정하지 않으면, Exception in thread “main” java.lang.NullPointerException: Cannot invoke “com.test.service.Section.getSectionCount()” because “this.sections[i]” is null 에러가 발생한다.
-
1) 코드 구현
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test_221221_1_1 { // 코드는 단계별로 주석처리로 진행했다.
public static void main(String[] args) throws IOException {
// 키워드 힌트가 필요하다면 열어보기!
//
// 문제 12 : 다음 각 문항에 답을 하시오.
//
// // 1. 다음 그림을 보고 Room 클래스와 Student 클래스를 작성하시오.
// // 2. 다음 코드는 App 클래스의 main 메소드 코드이다.
//
// Room room = new Room();
// room.load("res/students.csv");
// room.shuffle();
// room.print();
// room.sort();
// room.print();
//
//
// res/students.csv 파일내용을 읽어서 Room의 students 배열을 채우는 load() 코드를 작성하시오. students.csv 파일 내용은 다음과 같다.
//
// id,name
// 1,홍길동
// 2,강감찬
// 3,세종대왕
// 4,이순신
// 5,이방원
// 6,이성계
// 7,아이유
// 8,유재석
// 9,강호동
// 10,김종국
//
// // 3. students 배열을 랜덤하게 뒤섞는 shuffle() 메소드를 구현하시오.
// // 섞인 예는 다음과 같다.
//
// 6,이성계
// 3,세종대왕
// 2,강감찬
// 4,이순신
// 7,아이유
// 8,유재석
// 5,이방원
// 9,강호동
// 10,김종국
// 1,홍길동
//
// // 4. Room과 Student 클래스의 print() 메소드를 구현하시오.
//
//
// // 5. Room 클래스의 sort() 메소드를 구현하시오.
Room room = new Room();
room.load("res/students.csv");
room.shuffle();
room.print();
room.sort();
room.print();
}
}
package day.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Room {
Student[] students = new Student[10]; // 중요!! 배열 참조(나는 생성자에서 만드려고 했다.)
// 이건 공간만 만들어줌.
// ArrayList<Student> students; // 이게 배열에서 Composition 방식.
// public Room() {
// ArrayList<Student> students = new ArrayList<Student>();
// }
public void load(String path) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(path);
Scanner scan = new Scanner(fis);
while(scan.hasNext()) { // 데이터의 크기를 세는 방법 : 파일을 두번 읽어서 첫번째는 데이터 크기 세고 나머지는 그 크기는 배열 생성
// 두번째 방법은 : 가변배열 방법 이용
for(int j=0; j<10; j++) {
// line.replaceAll(",|\n", " "); // 이 방법으로도 나중에 해보기
String line = scan.nextLine();
String[] tokens = line.split(","); // 이부분은 위의 line과 같은 방식으로 String[]으로 생성한 부분이다.
// 참조 변수명이 여러개 값을 받으면 복수로 변수명 만들기
students[j] = new Student(); // 중요!! 배열 할당!!(내가 이해하지 못한 부분)
// 그 만들어진 공간에 이름 붙여주는 역할
int num = Integer.parseInt(tokens[0]);
students[j].setId(num);
students[j].setName(tokens[1]);
}
}
}
public void shuffle() {
Random rand = new Random();
for(int i=0; i<10; i++) {
int s = rand.nextInt(10);
int d = rand.nextInt(10);
Student temp; // 순서 바꾸기를 그냥 배열 요소 자체를 바꿔버림(주소끼리 바꾸는 느낌)
temp = students[s];
students[s] = students[d];
students[d] = temp;
}
}
public void print() {
for(int i=0; i<10; i++) {
students[i].print();
}
System.out.println();
}
public void sort() {
Student temp;
for(int j=0; j<10-1; j++) { // 버블 배열을 getId로 비교!
for(int i=0; i<10-1-j; i++) {
int currentId = students[i].getId(); // 이런식으로해서 조건을 이해할 수 있게 간단하게 만들자!
int nextId = students[i+1].getId(); // 이런식으로해서 조건을 이해할 수 있게 간단하게 만들자!
if(currentId > nextId){ // . 찍는 연산이나 []의 연산은 복잡도를 올려서 new로 다시 만들어주기!!
temp = students[i];
students[i] = students[i+1];
students[i+1] = temp;
}
}
}
}
}
package day.test;
public class Student {
int id;
String name;
public Student() { // 기본생성자가 없더라도 오버로드 생성자가 알아서 만들어준다. 하지만,
this(0,"newlec");
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print() {
System.out.printf("%d,%s\n",this.getId(),this.getName());
}
}
12. [22.12.22] : 문제 13. 지하철 시스템 만들기
package com.test.service;
public class SubwayController {
public static void main(String[] args) {
SubwayService ss = new SubwayService();
System.out.println("--------- Welcome Subway ---------");
ss.run();
}
}
package com.test.service;
import java.util.Scanner;
public class SubwayService {
boolean ox = true;
String[] subwaySections = {"1호차","2호차","3호차","4호차"};
String[] destinations = {"합정역","홍대입구역","신촌역","이대역","아현역"};
Section[] sections = new Section[4];
Station[] stations = new Station[5];
Station[][] detail = new Station[4][5];
int[] personCount = new int[4]; // 각 지하철역마다 사람수 count 변수 선언
int stationNum = 1;
int sectionNum = 0;
public void run() {
for (int i = 0; i < 4; i++) // 객체 배열 할당을 가장 처음에 해줘야지 while문 돌때마다 switch문 실행 시, 초기화가 되지 않는다.
sections[i] = new Section(); // 중요!! sections[i] 객체 배열 생성 이렇게 앞에 생성해서 뒤에서 여러번 사용한다. 배열 할당이면서 초기화 느낌
for (int i = 0; i < 5; i++) // 객체 배열 할당을 가장 처음에 해줘야지 while문 돌때마다 switch문 실행 시, 초기화가 되지 않는다.
stations[i] = new Station(); // 중요!! stations[i] 객체 배열 생성 이렇게 앞에 생성해서 뒤에서 여러번 사용한다. 배열 할당이면서 초기화 느낌
// 이부분 때문에 Person 객체 만들어야 할 수도... detail 2차원 배열을 하나로 합쳐야한다.****
// for (int j = 0; j < 5; j++)
// for (int i = 0; i < 5; i++) // 객체 배열 할당을 가장 처음에 해줘야지 while문 돌때마다 switch문 실행 시, 초기화가 되지 않는다.
// detail[j][i] = new Station(); // 중요!! detailStations[i] 객체 배열 생성 이렇게 앞에 생성해서 뒤에서 여러번 사용한다. 배열 할당이면서 초기화 느낌
Flag :
while(ox) {
System.out.println("=================================");
for(int i = 0; i<5; i++) {
System.out.println("현재역은 " + stations[i].getStationName() + "입니다.");
}
System.out.println("=================================");
System.out.println("메뉴를 선택해주세요.");
System.out.println("1. 탑승 // 2. 상세 상황 // 3. 이동 // 9. 종료");
Scanner scan = new Scanner(System.in);
switch (scan.nextLine()) {
case "1":
join();
break;
case "2":
status();
break;
case "3":
move();
break;
case "9":
System.out.println("열차운행을 종료합니다.");
break Flag;
default:
System.out.println("잘못 입력하셨습니다.");
}
}
}
private void join() {
Scanner scan = new Scanner(System.in);
System.out.println("------- 탑승가능 현황 -------");
for (int i = 0; i < 4; i++) {
//System.out.println(sections[i].getSectionCount());
if (sections[i].getSectionCount() < 4) {
System.out.println((i+1) + "호차 : 가능");
}
else if (sections[i].getSectionCount() == 4) {
System.out.println((i+1) + "호차 : 불가능");
}
if (sections[0].getSectionCount() == 4 && sections[1].getSectionCount() == 4 && sections[2].getSectionCount() == 4 && sections[3].getSectionCount() == 4) {
System.out.println("더이상 탑승 가능열차가 없습니다.");
}
}
System.out.println("어느 열차에 탑승하시겠습니까?");
for(int i =0; i<4; i++) { // 처음 열차 차량 설정
//sections[i] = new Section();
sections[i].setSectionNum(i+1);
sections[i].setSectionName(subwaySections[i]);
}
for(int i =0; i<4; i++) { // 처음 열차 차량 출력
sections[i].print();
}
System.out.println();
int section = Integer.parseInt(scan.nextLine()); // 새로운 열차 차량 입력
for(int i = 0 ; i <4; i++) {
if (section-1 == i) {
sections[i].setSectionCount(++personCount[i]); // 가고싶은 열차 차량의 사람수 count
sections[i].setSectionName(subwaySections[section-1]); // 가고싶은 열차 차량 출력
System.out.println(sections[i].getSectionName());
//System.out.printf("\n%d호차 : %d명\n", i+1, personCount[i]);
}
}
// 이부분 주의!!****
// for(int j = 0 ; j <4; j++) {
// for(int i = 0 ; i <4; i++) {
// if (section-1 == i) {
// detail[j][i].setSectionName(subwaySections[section-1]); // 가고싶은 열차 차량 출력
// System.out.println(sections[i].getSectionName());
// //System.out.printf("\n%d호차 : %d명\n", i+1, personCount[i]);
// }
// }
// }
// ---------------- 목적지 [station] ---------------------
System.out.println("목적지를 선택해주세요.");
for(int i =0; i<4; i++) { // 처음 목적지
stations[i].setStationNum(i+2);
stations[i].setStationName(destinations[i+1]);
}
for(int i =0; i<4; i++) {
stations[i].print();
}
System.out.println();
int stationNum = Integer.parseInt(scan.nextLine()); // 목적지 입력
for(int i =0; i<4; i++) { // 목적지 데이터 저장 -> 나중에 "상세내용" 부분에서 사용
if (stationNum-1 == i) {
stations[i].setStationNum(stationNum); // 가고싶은 목적지 출력
stations[i].setStationName(destinations[stationNum-1]); // 가고싶은 목적지 출력
}
}
// 중요한 부분!! "이동" 파트에서 쓰자****
// for(int i =0; i<4; i++) { // 탑승에서는 다음역으로 구간이 안 바뀌어도 된다. 이부분은 "이동" 부분에 넣어준다.
//
// stations[i].setStationNum(stationNum+i);
// stations[i].setStationName(destinations[stationNum+i]);
//
// if(stationNum + i == 4)
// stationNum = 1;
// }
//
// for(int i =0; i<4; i++) {
// stations[i].print();
// }
// System.out.println();
}
private void move() {
// 중요한 부분!! "이동" 파트에서 쓰자****
// for(int i =0; i<4; i++) { // 탑승에서는 다음역으로 구간이 안 바뀌어도 된다. 이부분은 "이동" 부분에 넣어준다.
//
// stations[i].setStationNum(stationNum+i);
// stations[i].setStationName(destinations[stationNum+i]);
//
// if(stationNum + i == 4)
// stationNum = 1;
// }
//
// for(int i =0; i<4; i++) {
// stations[i].print();
// }
// System.out.println();
}
private void status() {
}
}
package com.test.service;
public class Section {
private int sectionNum;
private String sectionName;
private int sectionCount;
public Section() {
this(1,"1호차",0);
}
public Section(int sectionNum, String sectionName, int sectionCount) {
this.sectionNum = sectionNum;
this.sectionName = sectionName;
this.sectionCount = sectionCount;
}
public int getSectionNum() {
return sectionNum;
}
public void setSectionNum(int sectionNum) {
this.sectionNum = sectionNum;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public int getSectionCount() {
return sectionCount;
}
public void setSectionCount(int sectionCount) {
this.sectionCount = sectionCount;
}
public void print() {
System.out.printf("%d. %s // ", this.sectionNum, this.sectionName);
}
}
package com.test.service;
public class Station {
private int stationNum;
private String stationName;
public Station() {
this(1, "합정역");
}
public Station(int stationNum, String stationName) {
this.stationNum = stationNum;
this.stationName = stationName;
}
public int getStationNum() {
return stationNum;
}
public void setStationNum(int stationNum) {
this.stationNum = stationNum;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
public void firstStation() {
System.out.printf("%s", this.stationName);
}
public void print() {
System.out.printf("%d. %s // ", this.stationNum, this.stationName);
}
}
13. [22.12.23] : 문제 13. 지하철 시스템(재수정)
package com.test.service;
public class SubwayController {
public static void main(String[] args) {
SubwayService ss = new SubwayService();
System.out.println("--------- Welcome Subway ---------");
ss.run();
}
}
package com.test.service;
import java.util.Scanner;
// **** 문제점1 : 새로운 목적지를 선택하면 그 목적지가 현재역으로 위치가 바뀜. ****** : [해결] - 약간의 로직 필요하며 현재역 출력 부분과 목적지 List 출력 부분을 따로 객체 변수로 getter, setter로 구현함
// **** 문제점2 : 이동하고 나서 목적지 List이 고정된 형태이다. ****** : [해결] -
// **** 문제점3 : 탑승 시, 스택처럼 쌓이지 않고 자리를 지정해서 앉는 느낌이다. - 해결하지 못하면, 승객 중에서 같은 목적지에서 내리는 승객을 처리할 수 없다!!(중복 처리)
// **** 문제점4 : 탑승 시, 현재역에서 현재역에 다시 탑승하면 다시 입력해달라고 할 것. 탑승하자마자 내려야하므로 (나중에 고치기) ****** : [해결하기] - do while 이용할 것
// **** 문제점 5 : 오입력 시, 다시 입력해야함. ****** : [해결하기] - do while 이용할 것
public class SubwayService {
boolean ox = true;
String[] subwaySections = {"1호차","2호차","3호차","4호차"};
String[] destinations = {"합정역","홍대입구역","신촌역","이대역","아현역"};
Section[] sections = new Section[4]; // 객체 지향으로 배열을 연결하기 위한 객체 배열 생성
Station[] stations = new Station[5];
Passenger[][] passengers = new Passenger[4][5];
int[] passengerCount = new int[4]; // 각 지하철역마다 사람수 count 변수 선언
int[] statonCount = new int[5];
int[] currentStationList = new int[5]; // 현재역 표시 인덱스
int[] nextStationList = new int[5]; // 목적지 업데이트 후 현재역 표시 인덱스
int stationNum = 0; // 상세 부분의 2차원 배열 인덱스
int sectionNum = 1; // 상세 부분의 2차원 배열 인덱스
int currentStream = -1; // 초기 목적지 List 인덱스
int nextStream = -1; // 목적지 선택 후 목적지 List 인덱스
public void run() {
for (int i = 0; i < 4; i++) // 객체 배열 할당을 가장 처음에 해줘야지 while문 돌때마다 switch문 실행 시, 초기화가 되지 않는다.
sections[i] = new Section(); // 중요!! sections[i] 객체 배열 생성 이렇게 앞에 생성해서 뒤에서 여러번 사용한다. 배열 할당이면서 초기화 느낌
for (int i = 0; i < 5; i++) // 객체 배열 할당을 가장 처음에 해줘야지 while문 돌때마다 switch문 실행 시, 초기화가 되지 않는다.
stations[i] = new Station(); // 중요!! stations[i] 객체 배열 생성 이렇게 앞에 생성해서 뒤에서 여러번 사용한다. 배열 할당이면서 초기화 느낌
for (int j = 0; j < 4; j++)
for (int i = 0; i < 5; i++)
passengers[j][i] = new Passenger();
Flag :
while(ox) {
System.out.println("=================================");
if(stations[0].getMoveCheck() == false)
System.out.println("현재역은 " + stations[0].getCurrentStation() + "입니다."); // 1-1) 초기값 설정으로 해결
else
System.out.println("현재역은 " + stations[0].getNextStation() + "입니다."); // 1-2) 추가 설정으로 해결
System.out.println("=================================");
System.out.println("메뉴를 선택해주세요.");
System.out.println("1. 탑승 // 2. 상세 보기 // 3. 이동 // 9. 종료");
Scanner scan = new Scanner(System.in);
switch (scan.nextLine()) {
case "1":
join();
break;
case "2":
status();
break;
case "3":
move();
break;
case "9":
System.out.println("열차운행을 종료합니다.");
break Flag;
default:
System.out.println("잘못 입력하셨습니다.");
}
}
}
private void join() {
Scanner scan = new Scanner(System.in);
System.out.println("------- 탑승가능 현황 -------");
for (int i = 0; i < 4; i++) {
if (sections[i].getSectionCount() < 4) {
System.out.println((i+1) + "호차 : 가능");
}
else if (sections[i].getSectionCount() == 4) {
System.out.println((i+1) + "호차 : 불가능");
}
if (sections[0].getSectionCount() == 4 && sections[1].getSectionCount() == 4
&& sections[2].getSectionCount() == 4 && sections[3].getSectionCount() == 4) {
System.out.println("더이상 탑승 가능열차가 없습니다.");
}
}
// ---------------- 열차 [section] ---------------------------------------------------------
System.out.println("어느 열차에 탑승하시겠습니까?");
for(int i =0; i<4; i++) { // 처음 열차 차량 설정
sections[i].setSectionNum(i+1);
sections[i].setSectionName(subwaySections[i]);
}
// 추가하기!! : 다음역을 반영하여 목적지 순서 나열 업데이트 출력 부분
for(int i =0; i<4; i++) { // 열차 차량 목록 출력
sections[i].print();
}
System.out.println();
sectionNum = Integer.parseInt(scan.nextLine()); // 타고 싶은 열차 차량 입력
for(int i = 0 ; i <5; i++) {
stations[i].setJoinCheck(true); // "탑승" 먼저 누르고 "이동" 누른 것을 체킹하기 위해서 *********
// (중요!! 배열 개수도 생각!! move메서드의 join 체킹을 위한 배열 개수 생각!)
if (i == sectionNum-1) {
sections[i].setSectionCount(++passengerCount[i]); // 타고 싶은 열차 차량의 사람수 count
sections[i].setSectionName(subwaySections[sectionNum-1]); // 타고 싶은 열차 차량 setting
System.out.println(sections[i].getSectionName());
}
}
// ---------------- 목적지 [station] ---------------------------------------------------------
// ** 에러 해결!! : 현재역 표시하는 메서드와 목적지를 표시하는 메서드를 따로 각각 구별해서 만들어줘야지 충돌하지 않는다!!!!
System.out.println("목적지를 선택해주세요.");
// 2-1) 첫 목적지 List 부분***** (목적지 List는 현재역을 빼고 나머지를 표시하므로 인덱스를 0~3까지만 출력 _ 원래는 5개여야하는데)
currentStream = 0;
for(int i =0; i<4; i++) { // 목적지 List 나열
if (destinations[i] == stations[0].getCurrentStation()) // 다음역 == 객체 배열 index
currentStream = i;
stations[i].setStationNum(currentStream+2);
stations[i].setStationName(destinations[++currentStream]);
if(currentStream == 4)
currentStream = -1;
}
// 2-2) 목적지 이동 후 목적지 List 부분***** (목적지 List는 현재역을 빼고 나머지를 표시하므로 인덱스를 0~3까지만 출력 _ 원래는 5개여야하는데)
for(int i =0; i<4; i++) { // 목적지 List 나열
if(stations[i].getMoveCheck() == true) {
if (destinations[i] == stations[0].getNextStation()) // 다음역 == 객체 배열 index
nextStream = i;
stations[i].setNextStationNum(nextStream+2);
stations[i].setNextStationName(destinations[++nextStream]);
if(nextStream == 4)
nextStream = -1;
}
}
// ** 목적지 List는 현재역을 빼고 나머지를 표시하므로 인덱스를 0~3까지만 출력 _ 원래는 5개여야하는데)
for(int i =0; i<4; i++) {
// move()가 동작 안 했으면 그대로 currentPrint가 동작하게
if(stations[i].getMoveCheck() == false) {
stations[i].currentListPrint();
}
else if(stations[i].getMoveCheck() == true) {
stations[i].nextListPrint();
}
}
System.out.println();
// ------ [상세내용 부분에서 쓸 내용] ------
stationNum = Integer.parseInt(scan.nextLine()); // 목적지 입력
for(int i =0; i<5; i++) { // 목적지 데이터 저장 -> 나중에 "상세내용" 부분에서 사용
if (i == stationNum-1) {
stations[i].setStationNum(stationNum); // 가고싶은 목적지 Num 세팅. 또한, 2차원 배열을 위한 칼럼 num 저장(나중의 "상세" 부분을 위해)
stations[i].setStationName(destinations[stationNum-1]); // 가고싶은 목적지 Name 세팅.
System.out.println(stations[i].getStationName());
}
}
for(int j =0; j<4; j++) { // 2차원 객체 배열의 각 요소 초기화 및 설정
// ** 지금 문제점 : 탑승하고 상세내역을 눌러야지 출력이 되고
for(int i =0; i<5; i++) { // 탑승을 바로 여러번하고 나서 상세내역을 뒤늦게 누르면 마지막 것만 출력이 된다.
if (i == stationNum-1 && j == sectionNum-1) // 전역 변수 주의!! 선언하면 초기화 되어서..
passengers[j][i].setpassengerRide(stations[i].getStationName());
}
}
}
private void move() {
// 1-1) 목적지 이동 후 현재역 출력을 위한 입력 부분 *****
for(int i =0; i<5; i++) { // 목적지 List 나열
stations[i].setMoveCheck(true);
if (destinations[i] == stations[0].getNextStation()) // 다음역 == 객체 배열 index
nextStationList[i] = i;
if(nextStationList[i] == 4)
nextStationList[i] = -1;
stations[i].setNextStation(destinations[++nextStationList[i]]);
}
// 1-2) 탑승을 먼저 눌렀을 경우,현재역 출력을 위한 입력부분
for(int i =0; i<5; i++) { // 목적지 List 나열
stations[i].setMoveCheck(true);
if(stations[i].getJoinCheck() == true) {
if (destinations[i] == stations[0].getNextStation()) { // 다음역 == 객체 배열 index
nextStationList[i] = i;
if(nextStationList[i] == 4)
nextStationList[i] = -1;
stations[i].setNextStation(destinations[++nextStationList[i]]);
}
}
}
// 3) 지하철역 하차 로직
int dropCount = 0;
for(int j =0; j<4; j++) { // 2차원 객체 배열의 각 요소 초기화 및 설정
// ** 지금 문제점 : 탑승하고 상세내역을 눌러야지 출력이 되고
for(int i =0; i<5; i++) { // 탑승을 바로 여러번하고 나서 상세내역을 뒤늦게 누르면 마지막 것만 출력이 된다.
if(stations[0].getNextStation() == "합정역" && passengers[j][i].getpassengerRide() == "합정역") {
passengers[j][i].setpassengerRide("없음");
dropCount++;
}
else if(stations[0].getNextStation() == "홍대입구역" && passengers[j][i].getpassengerRide() == "홍대입구역") {
passengers[j][i].setpassengerRide("없음");
dropCount++;
}
else if(stations[0].getNextStation() == "신촌역" && passengers[j][i].getpassengerRide() == "신촌역") {
passengers[j][i].setpassengerRide("없음");
dropCount++;
}
else if(stations[0].getNextStation() == "이대역" && passengers[j][i].getpassengerRide() == "이대역") {
passengers[j][i].setpassengerRide("없음");
dropCount++;
}
else if(stations[0].getNextStation() == "아현역" && passengers[j][i].getpassengerRide() == "아현역") {
passengers[j][i].setpassengerRide("없음");
dropCount++;
}
}
}
System.out.printf("%d명이 하차했습니다.", dropCount);
System.out.println();
System.out.println("현재역은 " + stations[0].getNextStation() + "입니다.");
}
private void status() {
// 4) 상세 내용을 보기 위한 로직
for(int j =0; j<4; j++) { // 2차원 객체 배열의 각 요소 초기화 및 설정
for(int i =0; i<5; i++) {
if (i == 0)
System.out.printf("%d호차 : [%s] ", j+1, passengers[j][i].getpassengerRide());
else
System.out.printf("[%s] ", passengers[j][i].getpassengerRide());
}
System.out.println();
}
}
}
package com.test.service;
public class Section {
private int sectionNum;
private String sectionName;
private int sectionCount;
public Section() {
this(1,"1호차",0);
}
public Section(int sectionNum, String sectionName, int sectionCount) {
this.sectionNum = sectionNum;
this.sectionName = sectionName;
this.sectionCount = sectionCount;
}
public int getSectionNum() {
return sectionNum;
}
public void setSectionNum(int sectionNum) {
this.sectionNum = sectionNum;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public int getSectionCount() {
return sectionCount;
}
public void setSectionCount(int sectionCount) {
this.sectionCount = sectionCount;
}
public void print() {
System.out.printf("%d. %s // ", this.sectionNum, this.sectionName);
}
}
package com.test.service;
public class Station {
private int stationNum;
private String stationName; // 초기의 목적지 List 출력을 위해
private int nextStationNum;
private String nextStationName; // 업데이트 된 목적지 List 출력을 위해
private String currentStation; // 현재역 표시를 위해
private String nextStation;
private boolean moveCheck; // 버튼 클릭 체킹을 위해
private boolean joinCheck;
public Station() {
this(1, "합정역", 1, "합정역", "합정역", "홍대입구역", false, false);
}
public Station(int stationNum, String stationName,int nextStationNum, String nextStationName, String currentStation, String nextStation, boolean moveCheck, boolean joinCheck) {
this.stationNum = stationNum;
this.stationName = stationName;
this.nextStationNum = nextStationNum;
this.nextStationName = nextStationName;
this.currentStation = currentStation;
this.nextStation = nextStation;
this.moveCheck = moveCheck;
this.joinCheck = joinCheck;
}
public int getStationNum() {
return stationNum;
}
public void setStationNum(int stationNum) {
this.stationNum = stationNum;
}
public int getNextStationNum() {
return nextStationNum;
}
public void setNextStationNum(int nextStationNum) {
this.nextStationNum = nextStationNum;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
public String getNextStationName() {
return nextStationName;
}
public void setNextStationName(String nextStationName) {
this.nextStationName = nextStationName;
}
public String getCurrentStation() {
return currentStation;
}
public void setCurrentStation(String currentStation) {
this.currentStation = currentStation;
}
public String getNextStation() {
return nextStation;
}
public void setNextStation(String nextStation) {
this.nextStation = nextStation;
}
public boolean getMoveCheck() {
return moveCheck;
}
public void setMoveCheck(boolean moveCheck) {
this.moveCheck = moveCheck;
}
public boolean getJoinCheck() {
return joinCheck;
}
public void setJoinCheck(boolean joinCheck) {
this.joinCheck = joinCheck;
}
public void currentListPrint() {
System.out.printf("%d. %s // ", this.stationNum, this.stationName);
}
public void nextListPrint() {
System.out.printf("%d. %s // ", this.nextStationNum, this.nextStationName);
}
}
package com.test.service;
public class Passenger {
private int passengerNum;
private String passengerRide;
public Passenger() {
this(0, "없음");
}
public Passenger(int passengerNum, String passengerRide) {
this.passengerNum = passengerNum;
this.passengerRide = passengerRide;
}
public int getPassengerNum() {
return passengerNum;
}
public void setPassengerNum(int passengerNum) {
this.passengerNum = passengerNum;
}
public String getpassengerRide() {
return passengerRide;
}
public void setpassengerRide(String passengerRide) {
this.passengerRide = passengerRide;
}
}