[Vector 클래스]

**Vector보다는 ArrayList를 쓰는 것이 좋다. 

**why? 버전이 업되면서 개선된 것이 ArrayList이기 때문에. 가급적 ArrayList를 쓰는 편이 좋다.

메서드/생성자 설명
Vector() 10개의 객체를 저장할 수 있는 Vector인스턴스 생성
*10개 이상의 인스턴스 저장 시, 자동으로 크기 증가
boolean add(Object o) Vector에 객체를 추가 *추가에 성공하면 true, 실패하면 false를 반환
boolean remove(Object o) Vector에 저장된 객체를 제거 *제거 후 Vector에 객체가 없으면 true, 있으면 false반환
boolean isEmpty() Vecotor가 비어 있는지 검사 
Object get(int index) index위치의 객체 주소 반환 
int size() Vecotor에 저장된 객체의 갯수 반환
package mymain;

import java.util.Vector;

public class VectorTest {

	public static void main(String[] args) {
		/*
		Product[] item = new Product[3];
		item[0] = new Tv();
		item[1] = new Audio();
		item[2] = new Computer();
		//AirConditioner를 넣을 공간이 없다.
		*/
		Vector<Product> item = new Vector<Product>(); //Product타입의 10개의 배열
		item.add(new Tv()); //순서대로 item[0] = new Tv();
		item.add(new Tv());
		item.add(new AirConditioner());
		item.add(new Computer());
		item.add(new Audio());
		System.out.println(item.get(0).toString());
		System.out.println(item.get(1).toString());
		System.out.println(item.get(2).toString());
		System.out.println(item.get(3).toString());
		System.out.println(item.get(4).toString());
		item.remove(item.get(1)); //삭제하면 빈 곳으로 객체주소 한칸씩 이동
		System.out.println("--------------------");
		System.out.println(item.get(0).toString());
		System.out.println(item.get(1).toString());
		System.out.println(item.get(2).toString());
		System.out.println(item.get(3).toString()); //4를 얻으려하면 에러 발생
		System.out.println("--------------------");
		System.out.println("item isEmpty? : "+item.isEmpty());
		System.out.println("--------------------");
		System.out.println("item 갯수 : "+item.size());
	}

}

class Product{}
class Tv extends Product{
	public String toString() {return "Tv";}
}
class Audio extends Product{
	public String toString() {return "Audio";}
}
class Computer extends Product{
	public String toString() {return "Computer";}
}
class AirConditioner extends Product{
	public String toString() {return "AirConditioner";}
}

>> 결과

Tv
Tv
AirConditioner
Computer
Audio
--------------------
Tv
AirConditioner
Computer
Audio
--------------------
item isEmpty? : false
--------------------
item 갯수 : 4

[ Single-ton 의 원리]

- 프로그램이 시작되었을 때 클래스변수, 클래스메서드가 메서드영역(클래스영역)에 적재되는 것을 응용
- 단순히 기능만 제공하는 서비스 객체(클래스)인스턴스반복적으로 생성해야할 때,
메모리의 불필요한 사용을 줄이고자 싱글톤을 사용한다.

<일상생활을 예로 이해하기 - 못 박기>

10번 못을 박기 위해,
1) 철물점에 가서 망치를 산다 -> 2) 못을 박는다.
2) 철물점에 가서 망치를 산다 -> 2) 못을 박는다.
3) 철물점에 가서....
x 10
-> 10번 못을 박기 위해,
1) 철물점에 가서 망치를 산다. -> 2) 못을 박는다.
1) 이미 사둔 망치를 또 쓰자 -> 2) 못을 박는다.
.......
x10


▼ 그림으로 표현한 싱글톤 원리


[예제_망치로 못을 박기]

package myutil;

public class MySingleTonTest {

	public static void main(String[] args) {
		int times = 10;
		for(int i = 0; i < times; i++) {
			Hammer hammer = Hammer.getInstance();
			hammer.nail();
		}
	}
	
}

class Hammer{
	public static Hammer single;
	
	protected Hammer(){}
	
	public static Hammer getInstance() {
		if(single == null) {
			single = new Hammer();
		}
		return single;
	} 
	
	public void nail() {
		System.out.println("못!");
	}
}

>> 결과

못!
못!
못!
못!
못!
못!
못!
못!
못!
못!


[ 자세한 내용 참조 링크 ]
https://velog.io/@kyle/%EC%9E%90%EB%B0%94-%EC%8B%B1%EA%B8%80%ED%86%A4-%ED%8C%A8%ED%84%B4-Singleton-Pattern

[참고]
국비과정 수업 내용참조

이클립스에서 패키지를 .jar로 내보내고 가져오기

[1] 패키지를 .jar형태로 Export 하기

내보내고 싶은 패키지를 선택하고 우측마우스&amp;gt;Export
JAR file은 .jar 라이브러리형식으로 내보내겠다는 의미다.
[1] 내보낼 패키지와 패키지 내 파일들 선택 [2] export할 장소 지정(여기에 저장된다)

 

[2] 내장된 .jar 가져오기

PATH를 지정해서, 지정된 경로에 있는 라이브러리를 가져오겠다는 의미

 

[3] 이제 사용가능한지 볼까?

** 어라? 소스코드를 볼 수 없다네. 왤까?

앞에서 export할 때, 소스코드도 같이 내보내겠다고 설정하지 않아서다.

>> 해결하는 법 : .jar 삭제하고 다시 export하자

 

[4] 코드 돌려보기 

잘 된다.

현재 디렉토리

 

1. 먼저 myutil 패키지 안에 myInfo클래스를 형성하고, 메소드를 작성했다.

-- 메서드 앞 public 접근제어자 : 어디서든 이 메서드 접근 가능

-- 메서드 앞 static 제어자 없음 : 인스턴스 형성 후 이 메서드 사용 가능

package myutil;

import java.util.Calendar;

public class MyInfo {
	
	//1. 띠 구하기
	//십이지 : 신유술해자축인묘진사오미 (0~11) 
	//식 : (현재년도 % 12)번째 십이지 (입 : int year, 출 : String)
	public String getTti(int year) {
		String[] Tti = {"원숭이", "닭", "개", "돼지","쥐", "소", "호랑이", 
		        "토끼","용","뱀", "말", "양",};
		int n = year % 12;
		return Tti[n];
	}
	
	//2. 간지 구하기
	//간지 : 경신임계갑을병정무기(0~9)
	//십이지 : 신유술해자축인묘진사오미 (0~11)
	//식 : (현재년도 % 10)번째 간지 + (현재년도 %12)번째 십이지 (입 : int year, 출 : String)
	public String getGanji(int year) {
		String[] Ganji = {"경","신","임","계","갑","을","병","정","무","기"};
		String[] Tti = {"신","유","술","해","자","축","인","묘","진","사","오","미"};
		int g = year % 10;
		int t = year % 12;
		
		return Ganji[g]+Tti[t];
	}
	
	
	//3. 출생년도로부터 나이 구하기 (입 : int year, 출 : int age)
	//   식 : 현재년도 - 출생년도 + 1
	public int getAge(int year) {
		//현재 년도
		Calendar c = Calendar.getInstance();
		int current_year = c.get(Calendar.YEAR);
		
		//식
		int age = current_year - year + 1;
		return age;
	}
}

 

2. mymain.Main1.java의 메인 함수에서 출력을 했다.

package mymain;

import java.util.Calendar;
import java.util.Scanner;

import myutil.MyInfo;

public class Main1 {

	public static void main(String[] args) {
		//출생년도를 통해 올해 띠, 간지, 나의 나이 구하기
		
		Scanner scanner = new Scanner(System.in);
		MyInfo myinfo = new MyInfo();
		Calendar c = Calendar.getInstance();
		
		System.out.print("당신의 출생년도를 입력하세요(ex.1994) : ");
		int user_year = scanner.nextInt();
		
		int current_year = c.get(Calendar.YEAR);
		
		System.out.printf("올해는 %d이며 %s의 해입니다.%n",current_year,myinfo.getTti(current_year));
		System.out.printf("올해는 %d이며 %s년입니다.%n",current_year,myinfo.getGanji(current_year));
		System.out.printf("올해는 %d이며 당신은 %d살이 되었습니다.%n",current_year,myinfo.getAge(user_year));
		
		scanner.close();
	}

}

>> 결과

당신의 출생년도를 입력하세요(ex.1994) : 1400
올해는 2022이며 호랑이의 해입니다.
올해는 2022이며 임인년입니다.
올해는 2022이며 당신은 623살이 되었습니다.

1. 최대값을 구하기

 

[1] 세 개의 양수 중 최대값 구하기

package practice2_Q;

import java.util.Scanner;

public class Q1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int[] arr = new int[3];
		System.out.print("세 개의 양수를 입력하세요 : ");
		arr[0] = scanner.nextInt();
		arr[1] = scanner.nextInt();
		arr[2] = scanner.nextInt();
		
		int max = 0;
		
		for(int i = 0; i < 3; i++) {
			if(max <= arr[i]) {
				max = arr[i];
			}
		}
		System.out.println("Max : "+max);
		
		scanner.close();
	}

}

>> 결과

세 개의 양수를 입력하세요 : 5 89 21
Max : 89

 

 

2. 입력받은 문자 읽기

 

[1] 사용자가 입력한 문자에서 알파벳 문자, 숫자, 화이트문자, 특수문자 갯수 출력

package practice2_Q;

import java.io.IOException;

public class Q2 {

	public static void main(String[] args) throws IOException{
		int ch = 0;
		int[] cnt = {0, 0, 0, 0}; //알파벳, 숫자, 화이트, 특수문자 순차 입력
		
		System.out.println("문자를 입력하세요(Ctrl+z하면 완료)");
		do
		{
			ch = System.in.read();
			
			if(ch == -1) break;
			
			System.out.printf("%c",ch);
			
			if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
				cnt[0]++; //알파벳
			}else if(ch >= '0' && ch <= '9') {
				cnt[1]++; //숫자
			}else if(ch == '\r' || ch == '\n' || ch == ' ' || ch == '\t'){
				cnt[2]++; //화이트문자
			}else {
				cnt[3]++; //기타(특수기호)
			}
		}while(true);
		System.out.println();
		System.out.println("알파벳   : "+cnt[0]);
		System.out.println("숫자     : "+cnt[1]);
		System.out.println("화이트   : "+cnt[2]);
		System.out.println("특수문자 : "+cnt[3]);	

	}

	
}

>> 결과

문자를 입력하세요(Ctrl+z하면 완료)
hey there, wanna hang out? :)
hey there, wanna hang out? :)

알파벳   : 20
숫자     : 0
화이트   : 7
특수문자 : 4

 

[2] 사용자로부터 두 개의 양수와 연산자를 받아 계산하기 

package practice2_Q;

import java.util.Scanner;

public class Q3 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("두 개의 양수와 연산자를 입력하세요 : ");
		int x = scanner.nextInt();
		int y = scanner.nextInt();
		String z = scanner.next();
		int result = 0;
		
		switch(z){
			case "+" : result = x + y; break;
			case "-" : result = x - y; break;
			case "*" : result = x * y; break;
			case "/" : result = x / y; break;
			case "%" : result = x % y; break;
			default  : result = -1;
		}
		System.out.printf("%d %s %d = %d",x,z,y,result);
		
		scanner.close();
	}

}

>> 결과

두 개의 양수와 연산자를 입력하세요 : 2 3 +
2 + 3 = 5

 

[3] 사용자로부터 알파벳 문자를 하나 받아 나라명 출력하기 (if - else문 활용)

package practice2_Q;

import java.io.IOException;

public class Q4 {

	public static void main(String[] args) throws IOException {
		String[] nation = {"America","Bangladesh", "Canada", "Demmark","Ezypt", "France", 
				"Greece","Hungary","Iceland","Jamaica","Korea",
				"Lebanon","Malta","North Korea","Oman","Peru","Qatar","Romania","Singapore",
				"Thailand","Uganda","Vietnam","W로 시작하는 나라는 없습니다.","X로 시작하는 나라는 없습니다.","Yemen","Zambia"};
		String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		
		System.out.print("문자 한 개를 입력하세요. >> ");
		int ch = System.in.read();
		
		//소문자 -> 대문자
		if(ch >= 'a' || ch <= 'z') ch -= 32;

		for(int i = 0; i < alpha.length(); i++) {
			if(ch == alpha.charAt(i)) {
				System.out.printf("%c로 시작하는 나라는 : %s",ch,nation[i]);
			}
		}
	}

}

>> 결과

문자 한 개를 입력하세요. >> a
A로 시작하는 나라는 : America

 

3. 사칙연산 결과를 테이블 형식으로 출력 

 

[1] 정상가격과 세일가격(30%) 출력하기 (정상가격 범위 : 20000원~30000원)

package practice2_Q;

public class Q5 {

	public static void main(String[] args) {
		System.out.println("정상가격      세일가격");
		System.out.println("--------------------------");//14
		
		for(int price = 20000; price <= 30000; price+=1000) {
			System.out.printf("%-13d %.0f\n",price,price*0.7);
		}
	}

}

>> 결과

 

정상가격      세일가격
--------------------------
20000         14000
21000         14700
22000         15400
23000         16100
24000         16800
25000         17500
26000         18200
27000         18900
28000         19600
29000         20300
30000         21000

 

[2] 사용자에게 양의 정수 n을 받아, 1부터 n까지 합 구하기 

package practice2_Q;

import java.util.Scanner;

public class Q6 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("양수 n : ");
		int n = scanner.nextInt();
		int sum = 0;
		
		for(int i = 1; i <= n; i++) {
			sum += i;
		}
		System.out.println("sum : "+sum);
		
		scanner.close();
	}

}

>> 결과

양수 n : 5
sum : 15

 

[3] 1부터 10까지 양의 정수 중 짝수의 곱을 구하기

package practice2_Q;

public class Q7 {

	public static void main(String[] args) {
		int n = 10;
		int result = 1;
		
		for(int i = 1; i <= n; i++) {
			if(i % 2 == 0)
				result = result * i;
		}
		System.out.println("result : "+result);
	}

}

>> 결과

result : 3840

 

[4] 원주율을 구하는 공식에 따라 원주율 값 구하기

4/1 - 4/3 + 4/5 - 4/7 + 4/9 .....
package practice2_Q;

public class Q8 {
	public static void main(String[] args) {
		int n = 1;
		int sign = 1;
		double result = 0;
		for(long i = 0; i < 2000000000; i++) {
			result += sign*(4.0/n);
			sign = -sign;
			n += 2;
		}
		System.out.println("PI = "+result);
	}
}

>> 결과

PI = 3.141592658505181

 

4. 제곱과 팩토리얼

 

[1] (제곱) 0~6까지의 제곱과 세제곱을 구하여 테이블 형식으로 출력

package practice2_Q;

public class Q9 {

	public static void main(String[] args) {
		System.out.println("기존      제곱      세제곱");
		System.out.println("-----------------------------");
		
		for(int i = 0; i < 7; i++) {
			System.out.printf("%-10d%-10d%d%n",i,i*i,i*i*i);
		}
	}

}

>> 결과

기존      제곱      세제곱
-----------------------------
0         0         0
1         1         1
2         4         8
3         9         27
4         16        64
5         25        125
6         36        216

 

[2] (팩토리얼) 사용자에게 양의 정수 n을 받아, n! 구하기 (n! = n * (n-1)! // 단, 0!은 1이다)

package practice2_Q;

import java.util.Scanner;

public class Q10 {

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("n값 : ");
		long n = scanner.nextInt();
		long result = 1;
		
		//f(x) = x * f(x-1) 
		//단, x가 0일 때 값은 1이다.
		if(n == 0) {
			result = 1;
		}else {
			for(long i = n; i > 0; i--) {
				result = result * i; 
			}
		}
		System.out.printf("%d! = %d",n,result);

		scanner.close();
	}
	
}

>> 결과

n값 : 3
3! = 6

 

[※ 참고 : 팩토리얼 원리]
- 팩토리얼이란 무엇일까? https://johnleeedu.tistory.com/23
- 팩토리얼을 왜 사용하나?
  https://ko.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/the-factorial-function
- 팩토리얼의 수학 원리 https://www.youtube.com/watch?v=zSUMcsASTTo 

팩토리얼은 고등수학에서 순열과 조합을 배우면서 배우는 것인데, 경우의 수를 구할 때 사용한다.
원리는 다음과 같다.
만약 A,B,C 세 사람이 앉는 순서를 정한다 할 때 경우의 수는 아래처럼 구할 수 있다.

0!이 1인 이유는, 아무것도 없을 때에 "없다"는 것도 하나의 경우에 해당하기 때문

 

[3] 실수의 거듭 제곱 값 구하기 (실수 : r, 정수 : n)

package practice2_Q;

import java.util.Scanner;

public class Q11 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("실수, 정수를 하나씩 입력하세요.(ex.5.34 7)");
		double r = scanner.nextDouble();
		int n = scanner.nextInt();
		double result = 1;
		
		for(int i = 0; i < n; i++) {
			result = result * r;
		}
		System.out.printf("%f^%d = %f",r,n,result);
		
		scanner.close();
	}
}

>> 결과

실수, 정수를 하나씩 입력하세요.(ex.5.34 7)
5.231    3
5.231000^3 = 143.137741

구구단/행렬/별찍기 모두 원리는 비슷했다. 

결국 수학의 (x , y) 행렬이라 볼 수 있는데, 중첩 for문을 사용해서 구현이 가능하다.

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

 

1. 구구단 예제

 

[1] 구구단 2~9단을 출력하라_중첩 for문 활용

package practice;

public class dan99TestBasic {

	public static void main(String[] args) {
		for(int i = 2; i <= 9; i++) {
			System.out.println("--------["+i+"단 시작]--------");
			for(int j = 1; j <= 9; j++) {
				System.out.printf("%d x %d = %2d%n",i,j,i*j);
			}
		}
	}

}

>> 결과

--------[2단 시작]--------
2 x 1 =  2
2 x 2 =  4
2 x 3 =  6
2 x 4 =  8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
--------[3단 시작]--------
3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
--------[4단 시작]--------
4 x 1 =  4
4 x 2 =  8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
--------[5단 시작]--------
5 x 1 =  5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
--------[6단 시작]--------
6 x 1 =  6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
--------[7단 시작]--------
7 x 1 =  7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
--------[8단 시작]--------
8 x 1 =  8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
--------[9단 시작]--------
9 x 1 =  9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81

 

[1-2] 사용자가 입력한 x단의 구구단을 출력하라_do_while 활용

(단, 사용자는 여러 번 구구단을 입력하고 결과를 받을 수 있어야 한다.)

package practice;

import java.util.Scanner;

public class Dan99Test2 {

	public static void main(String[] args) {
				
		int dan = 0;
		String yn = "Y";
		Scanner scanner = new Scanner(System.in);
		
		do
		{
			System.out.print("단 입력(2~9단 중 하나) : ");
			dan = scanner.nextInt();
			
			if(dan >= 2 && dan <= 9) {
				for(int i = 1; i <=9; i++) {
					System.out.printf("%d x %d = %2d\n",dan,i,dan*i);
				}
				System.out.print("더 하시겠습니까? (y/n) :");
				yn = scanner.next();
			}else {
				System.out.println("2~9 중 하나를 입력해주세요.");
			}
		}while(yn.equals("Y") || yn.equals("y"));
			
		scanner.close();
	}

}

>> 결과

단 입력(2~9단 중 하나) : 3
3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
더 하시겠습니까? (y/n) :n

 

2. 행렬

 

[1] 아래와 같은 형태의 행렬을 출력하라.

>> 결과1

(1,1) (1,2) (1,3) (1,4) (1,5) 
(2,1) (2,2) (2,3) (2,4) (2,5) 
(3,1) (3,2) (3,3) (3,4) (3,5) 
(4,1) (4,2) (4,3) (4,4) (4,5) 
(5,1) (5,2) (5,3) (5,4) (5,5)

 

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {
		//중첩for문_행렬 구하기
		int row = 5;
		int col = 5;
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				System.out.printf("(%d,%d) ",i, j);
			}
			System.out.println();
		}
	}

}

 

[2] 아래와 같이 좌->우로 내려오는 대각선에 공백을 둔 행렬을 출력하라

>> 결과

( , ) (1,2) (1,3) (1,4) (1,5) 
(2,1) ( , ) (2,3) (2,4) (2,5) 
(3,1) (3,2) ( , ) (3,4) (3,5) 
(4,1) (4,2) (4,3) ( , ) (4,5) 
(5,1) (5,2) (5,3) (5,4) ( , )

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {	
		//중첩for문+continue_행렬에서 i==j값 공백
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				if(i == j) {
					System.out.printf("( , ) ",i, j);
					continue;
				} 
				System.out.printf("(%d,%d) ",i, j);
			}
			System.out.println();
		}
	}

}

 

[3] 아래와 같이 좌->우로 내려오는 대각선에 공백을 두고, 대각선의 우측은 제외하여 출력하라.

>> 결과

( , ) 
(2,1) ( , ) 
(3,1) (3,2) ( , ) 
(4,1) (4,2) (4,3) ( , ) 
(5,1) (5,2) (5,3) (5,4) ( , )

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {
		//중첩for문+continue label_행렬에서 i==j값 공백, i<j면 미출력
		OUT_FOR : 
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				if(i == j) {
					System.out.printf("( , ) ",i, j);
					continue;
				}else if(i < j) {
					System.out.println();
					continue OUT_FOR;
				}else {
					System.out.printf("(%d,%d) ",i, j);
				}
			}
			System.out.println();
		}
	}

}

 

3. 별찍기

 

 [1] 정사각형 별찍기

package practice;

public class StarTest1 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

}

>> 결과

*****
*****
*****
*****
*****

 

[2] 반피라미드 - 좌->우 대각선 하위만 출력

package practice;

public class StarTest2 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(j <= i) {
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

*
**
***
****
*****

 

[3] 역 반피라미드 - 좌->우 대각선 상위만 출력

package practice;

public class StarTest3 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(j >= i) {
					System.out.print("*");
				}else {
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

*****
 ****
  ***
   **
    *

 

[4] 바람개비 - 좌->우, 우->좌 대각선 제외 출력 

package practice;

public class StarTest4 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(i == j || 4-j==i) {
					System.out.print(" ");
				}else {
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

 *** 
* * *
** **
* * *
 ***

 

[4-2] 반피라미드 - 우->좌 대각선 하위만 출력 (그림에 이걸 빼먹었다..ㅎ)

package practice;

public class StarTest6 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = col-1; j >= 0; j--) {
				if(j <= i) {
					System.out.print("*");
				}else {
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

    *
   **
  ***
 ****
*****

 

[5] 마름모 출력하기

package practice;

public class StarTest5 {

	public static void main(String[] args) {
		int n = 5;
		int mid = n/2;
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if(i <= mid) { //상단
					//가운데를 기준으로,
					//2-i <= j <= 2+i 일때에 출력
					if((j >= mid-i) && (j <= mid+i)) {
						System.out.print("*");
					}else {
						System.out.print(" ");
					}
				}else { //하단
					int k = (n-1)-i; //임시변수k 새로 만들어줘야함
					if((j >= mid-k) && (j <= mid+k)) {
						System.out.print("*");
					}else {
						System.out.print(" ");
					}
				}
			}
			System.out.println();
		}
	}

}

>> 결과

  *  
 *** 
*****
 *** 
  *

 

 

+ Recent posts