package com.KoreaIT.java.AM;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		System.out.println("==프로그램 시작==");
		Scanner sc = new Scanner(System.in);
		int lastArticleId = 0;
		List<Article> articles = new ArrayList<>();
		while (true) {
			System.out.print("명령어 > ");
			String command = sc.nextLine();
			if (command.length() == 0) {
				System.out.println("명령어를 입력해주세요");
				continue;
			}
			if (command.equals("exit")) {
				break;
			}
			if (command.equals("article list")) {
				if (articles.size() == 0) {
					System.out.println("게시글이 없습니다");
				} else {
					System.out.println(" 번호  //  제목  ");
					for (int i = articles.size() - 1; i >= 0; i--) {
						Article article = articles.get(i);
						System.out.printf("  %d   //   %s  \n", article.id, article.title);
					}
				}

			} else if (command.equals("article write")) {

    
          
            
    

          
    
    
  
				int id = lastArticleId + 1;
				System.out.print("제목 : ");
				String title = sc.nextLine();
				System.out.print("내용 : ");
				String body = sc.nextLine();
				Article article = new Article(id, title, body);
				articles.add(article);
				System.out.printf("%d번글이 생성되었습니다\n", id);
				lastArticleId++;
			} else {
				System.out.println("존재하지 않는 명령어입니다");
			}
		}
		System.out.println("==프로그램 끝==");
		sc.close();
	}
}
class Article {
	int id;
	String title;
	String body;
	Article(int id, String title, String body) {
		this.id = id;
		this.title = title;
		this.body = body;
	}
}

 

aritle list 기능이 완성 되어간다

글이  없으면 없다하고 있으면 있던데? 보다는 코드적으로 글의 목록을 표현 하고싶다

else{

System.out.println("번호  //  제목");

for (int i = articles.size() - 1 ; i>= 0 ; i --);

   Aricle article = aricles.get(i);

   System.out.print("   %d    //   %s    \n ",article.id, article.title);

 

코드를 추가한다

 

위 코드는 리스트 articles에 저장된 게시물 정보를 출력하는 코드로 먼저 "번호 // 제목"을 출력하고, 리스트의 뒤에서부터 순회하면서 각 게시물의 id와 title을 출력한다 (명령어) article list를 입력했을 때 일어나는 일이다)

for 루프는 리스트 articles의 끝에서부터 시작하여 i 변수를 1씩 감소시키면서 반복한다. 각 반복에서 articles.get(i)를 통해 현재 위치의 게시물 정보를 가져와 article 변수에 저장한다

articles.size() - 1을 하는 이유는 리스트의 인덱스가 0부터 시작하기 때문. articles.size()는 리스트의 원소 개수를 반환하므로, 인덱스가 0부터 시작하면 마지막 원소의 인덱스는 size() - 1가 된다.

마지막으로 System.out.print()를 통해 " %d // %s \n" 형식의 문자열을 출력. %d는 정수를, %s는 문자열을 대체할 수 있는 포맷 문자열이다. 이 때, 포맷 문자열 내에 %d와 %s가 있음에도 불구하고, System.out.print() 메소드는 두 번째 인자부터 포맷 문자열에 포함될 값을 차례로 전달해야 함. 따라서 위 코드에서는 article.id와 article.title을 각각 %d와 %s에 대입하여 보여준다. 그럼 번호 , 제목이 나오겠지 

최종적으로 위 코드는 리스트 articles의 모든 게시물 정보를 역순으로 출력

실행결과? 내 의도대로 나온다

+ Recent posts