Java practice_240103

Choi Suyeon·2024년 1월 3일

Main method arguments

  • argument(인수)
package day0103;
/**
 * main method의 arguments 입력과 사용에 대한 연습.<br>
 * 
 * 실행) java day0103.TestArguments 값 값 값......
 */
public class TestArguments {

	public static void main(String[] args) {

		System.out.println(args[0]);//args[0]=11
		System.out.println(args[1]);//args[1]=18
		System.out.println(args[2]);//args[2]=20
		//문자열(String)은 연산되지 않는다.
		System.out.println(args[0] + args[1]);//1118
		
		//int i = args[0]; 참조형은 기본형에 할당할 수 없다.
		//int i = (int)args[0]; 문자열을 기본형으로 강제형변환할 수 없다.
		
		//문자열을 정수로 변환하는 일(method)을 하는 method를 사용.
		int num = Integer.parseInt(args[0]);//Integer.parseInt 문자열을 정수로 바꿈
		int num2 = Integer.parseInt(args[1]);	
		System.out.println(num + " + " +  num2 + " = " + (num + num2));//11 + 18 = 29
		
	}//main

}//class

if문

단일 if

  • 조건에 맞을 때에만 코드를 실행해야 하는 경우
문법) 

if(조건식) {
   조건에 맞을 때 수행할 문장들....
 }
package day0103;
public class TestIf {

	public static void main(String[] args) {

		//main method에 처음 입력된 arguments 임의의 수의 절대값을 구하여 출력.
		//int num=-12;
		int num = Integer.parseInt(args[0]);
		int abs = num;
		
		if (num < 0) {//임의의 수가 0보다 작으면 음수 이므로 true가 발생하고 if 탄다.
			abs = -num;//2의 보수연산을 수행		
		}//end if
		
		System.out.println(num + "의 절대값은 " + abs);
		
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		
		//문자열의 비교는 "같은지만" 비교할 수 있고, 관계연산자를 사용하는 것이 아닌
		//equals method를 사용하여 비교한다.
		System.out.println("equals 문자열의 비교 : " + args[0].equals("-48"));
		System.out.println("equals 문자열의 비교 : " + args[0].equals("-47"));
		
		//main method에 두번째 입력된 arguments는 성별(남, 여)이다. 
		//프로그램의 출력은 입장 > 여자인 경우 "수건 2장 지급" > 목욕탕입실 의 순서로 출력.
		
		System.out.println(args[1] + "성별이 입력되었습니다.");
		System.out.println("출입문 입장");
		
		if(args[1].equals("여자")) {//문자열의 비교
		System.out.println("수건 2장 지급");//이 코드는 "여자"일 때만 실행.
		}//end if
		
		System.out.println("목욕탕 입실");
		
		//실수의 비교
		//사람이 활동하기 좋은 날씨는 25.0 ~ 30.0도 이다. 
		//이 온도일때만 "좋은 날씨입니다. (0^~^0)"를 출력.
		
		double temperature=27.5;
		System.out.println("현재온도 : " + temperature);
		if((temperature > 25) && (temperature <= 30.0)) {//25도 초과, 30도 이하로 조건 만들기
			System.out.println("좋은 날씨입니다. (0^~^0)");
		}//end if
		if((temperature < 25) || (temperature >= 30.0)) {//25도 초과, 30도 이하로 조건 만들기
			System.out.println("이상기후입니다. 외출시 조심하세요");
		}//end if
		
		//문자의 비교
		//char의 변수에는 임의의 문자가 들어있다. 해당 문자가 대문자일 때만 "대문자"를 출력.
		//해당 문자가 대문자일때만 "대문자"를 출력(A(65)~Z(90))
		char temp = 'A';
		System.out.print(temp);
		if(temp > 64 && temp < 91) {
			System.out.println("는 대문자");
		}//end if
		
	}//main

}//class

else

  • if~else : 둘 중 하나의 코드를 실행해야 할 때 사용.
문법) 

 if(조건식){ 
  	조건에 맞을 때 수행할 문장 들... 
 } else{ 
  	조건에 맞지 않을 때 수행할 문장 들.... }
package day0103;
public class TestIfElse {

	public static void main(String[] args) {

		// 임의의 정수가 홀수 인지 짝수인지 구별하여 출력하는 코드.
		int i = 3;

		System.out.print(i + "는(은)");
		if (i % 2 != 0) {
			System.out.println("홀수");
		} else {
			System.out.println("짝수");
		} // end if

		// 임의의 점수를 저장하는 변수를 만들고, main method arguments 첫번째를 받아서
		// 0~100이면 "유효점수" 출력하고, 그렇지 않다면 "무효점수"를 출력.
		int x = Integer.parseInt(args[0]);
		if (x > -1 && x < 101) {
			System.out.println(x + "는 유효점수");
		} else {
			System.out.println(x + "는 무효점수");
		}//end else
		
	}// main

}// class

다중 if

  • (else ~ if) : 연관된 여러 조건을 비교할 때 사용
문법) 
if(조건식){ 
	조건에 맞을 때 수행할 문장들... 
}else{ 
	조건에 맞지 않을 때 수행할 문장들.. 
}
package day0103;

/**
 * 다중 if 
 * 
 * 문법) if(조건식){ 조건에 맞을 때 수행할 문장들... }else{ 조건에 맞지 않을 때 수행할 문장들.. }
 */
public class TestElseIf {

	// public static final int MONKEY = 0;

	public static void main(String[] args) {

		// 점수 판별
		// 점수는 0보다 작을 수 없고, 100보다 클 수 없다.
		// 0보다 작다면, "0보다 작아서 실패" 출력하고
		// 100보다 크다면, "100보다 커서 실패" 출력하고
		// 그렇지 않다면(0~100 사이) "성공"을 출력

		int score = 101;
		if (score < 0) {
			System.out.println("0보다 작아서 실패");
		} else if (score > 100) {
			System.out.println("100보다 커서 실패");
		} else {
			System.out.println("성공");
		} // end else

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		// char 형의 변수에는 임의의 문자가 할당되어있다.
		// 할당된 문자가 "대문자(65-90)"인지, "소문자(97-123)"인지, "숫자(48-58)"인지
		// 그렇지 않다면 "영어나 숫자가 아닙니다."
		char word = 'a';
		if (word > 64 && word < 91) {

			System.out.println(word + "는 대문자입니다.");

		} else if (word > 96 && word < 123) {

			System.out.println(word + "는 소문자입니다.");

		} else if (word > 47 && word < 58) {

			System.out.println(word + "는 숫자입니다.");

		} else {

			System.out.println("영어나 숫자가 아닙니다.");

		} // end else
  • 태어난 해를 저장하는 변수를 선언하고, 자신의 태어난 해를 할당한다.
    태어난 해의 띠를 출력.
    0-원숭이, 1-닭, 2-개, 3-돼지, 4-쥐, 5-소, 6-호랑이, 7-토끼, 8-용, 9-뱀, 10-말, 11-양
  • constant 사용(가독성을 올리기 위해)
package day0103;

public class Zodiac {
	// 0-원숭이, 1-닭, 2-개, 3-돼지, 4-쥐, 5-소, 6-호랑이, 7-토끼, 8-용, 9-뱀, 10-말, 11-양

	/**
	 * 원숭이
	 */
	public static final int MONKEY = 0;
	/**
	 * 닭
	 */
	public static final int ROOSTER = 1;
	/**
	 * 개
	 */
	public static final int DOG = 2;
	/**
	 * 돼지
	 */
	public static final int PIG = 3;
	/**
	 * 쥐
	 */
	public static final int RAT = 4;
	/**
	 * 소
	 */
	public static final int COW = 5;
	/**
	 * 호랑이
	 */
	public static final int TIGER = 6;
	/**
	 * 토끼
	 */
	public static final int RABBIT = 7;
	/**
	 * 용
	 */
	public static final int DRAGON = 8;
	/**
	 * 뱀
	 */
	public static final int SNAKE = 9;
	/**
	 * 말
	 */
	public static final int HORSE = 10;
	/**
	 * 양
	 */
	public static final int LAMB = 11;

	public static void main(String[] args) {

	}

}

출력

		int birth_year = 2024;
		if (birth_year % 12 == Zodiac.MONKEY) {
			System.out.println(birth_year + "년생은 원숭이 띠입니다.");
		} else if (birth_year % 12 == Zodiac.ROOSTER) {
			System.out.println(birth_year + "년생은 닭 띠입니다.");
		} else if (birth_year % 12 == Zodiac.DOG) {
			System.out.println(birth_year + "년생은 개 띠입니다.");
		} else if (birth_year % 12 == Zodiac.PIG) {
			System.out.println(birth_year + "년생은 돼지 띠입니다.");
		} else if (birth_year % 12 == Zodiac.RAT) {
			System.out.println(birth_year + "년생은 쥐 띠입니다.");
		} else if (birth_year % 12 == Zodiac.COW) {
			System.out.println(birth_year + "년생은 소 띠입니다.");
		} else if (birth_year % 12 == Zodiac.TIGER) {
			System.out.println(birth_year + "년생은 호랑이 띠입니다.");
		} else if (birth_year % 12 == Zodiac.RABBIT) {
			System.out.println(birth_year + "년생은 토끼 띠입니다.");
		} else if (birth_year % 12 == Zodiac.DRAGON) {
			System.out.println(birth_year + "년생은 용 띠입니다.");
		} else if (birth_year % 12 == Zodiac.SNAKE) {
			System.out.println(birth_year + "년생은 뱀 띠입니다.");
		} else if (birth_year % 12 == Zodiac.HORSE) {
			System.out.println(birth_year + "년생은 말 띠입니다.");
		} else if (birth_year % 12 == Zodiac.LAMB) {
			System.out.println(birth_year + "년생은 양 띠입니다.");
		} else {
			System.out.println("출생년도를 다시 입력하세요.");
		}
        
	} // main
    
}// class

0개의 댓글