Algorithms/Java

Java: 쉽게 배우는 자바1 정리

Jenn28 2023. 1. 16. 17:04

부스트코스에 있는 생활코딩님의 쉽게 배우는 자바1 강의를 듣기 시작했다.

까먹지 않도록 정리해놔야겠다!


 

파이썬과 다르게 문자*문자가 안된다. + '작은 따옴표'는 한글자만 표현 할 수 있다.

파이썬에서 문자열 길이 함수는 len()이였는데 자바에서는 .length()이다.

public class Datatype{
	public static void main(String[] args) {
		System.out.println(6); //Number
		System.out.println("six"); //String
		System.out.println(6+6); //12
		System.out.println("6"+"6"); //66
//		System.out.println("6"*"6"); 파이썬에서는 가능하지만 자바에서는 x
		System.out.println("1111".length()); //4 문자열 길이, 파이썬으로 치면 len()
		System.out.println();
	}
}

 

자바에서는 따로 import math 안해도 바로 쓸 수 있는 것 같다. + PI를 꼭 대문자로 써야하는 것 같다.

Math.floor(): 뒤 소수점 자르기

Math.ceil(): 앞으로 up 시키기

public class Number {
	public static void main(String[] args) {
		System.out.println(6+2); //8
		System.out.println(6*2); //12
		System.out.println(6/2); //3
		
		System.out.println(Math.PI);
		System.out.println(Math.floor(Math.PI)); //floor: 뒤 소수점 짤라버리기
		System.out.println(Math.ceil(Math.PI)); //ceil: 뒤 소수점 1이면 앞으로 up시켜서 올려버리기
	}
}

 

줄바꿈: \n

글자 안에 따옴표: "Hello \"World\""

 

"[[[name]]]".replace("[[[name]]]", "egoing"): 약간 { }.format() 느낌인거같다.

--> "[name]".replace("[name]", "egoing")도 가능

public class StringOperation {
	public static void main(String[] args) {
		System.out.println("Hello World".length());
		System.out.println("Hello, [[[name]]] ... bye.".replace("[[[name]]]", "egoing"));
	}
}

 

변수 선언

- int a: 정수

- double a: 실수(소수)

- String a: 문자열

 

여기서 큰 차이는 double을 int로 변환 시 뒷자리는 잃어버린다.

public class Casting {
	public static void main(String[] args) {
		double b=1;
		System.out.println(b);
		
		double d=1.1;
		int e=(int)1.1; //소수는 수동으로 변환해줘야함 -> 뒷자리 잃어버림
		System.out.println(e);
		
		String f=Integer.toString(1); //int를 str로 변환
		System.out.println(f);
		System.out.println(f.getClass()); //클래스 타입 뭔지
	}
}

 

IoT 프로그램 만들기

import org.opentutorials.iot.Elevator;
import org.opentutorials.iot.Lighting;
import org.opentutorials.iot.Security;

public class OkJavaGoingHome {
	public static void main(String[] args) {
		
		String id="JAVA APT 507";
				
		// Elevator call
		Elevator myElevator=new Elevator(id);
		myElevator.callForUp(1);
		
		// Security off
		Security mySecurity=new Security(id);
		mySecurity.off();
		
		// Light on
		Lighting hallLamp=new Lighting(id+" / Hall Lamp");
		hallLamp.on();
		Lighting floorLamp=new Lighting(id+" / floorLamp");
		floorLamp.on();
	}
}

 

입력과 출력

- String id=JoptionPane.showInputDialog("Enter a id"): 새 창 띄우고 input 받음

- String id=args[0]: run configuration에서 arguments 설정

 

나의 앱 만들기

- String->Double: Double.parseDouble(args[0])

- 조건문

public class AccountingIFApp {
	public static void main(String[] args) {
    
		double valueOfSupply = Double.parseDouble(args[0]);
		double vatRate = 0.1;
		double expenseRate = 0.3;
		double vat = valueOfSupply*vatRate;
		double total = valueOfSupply+vat;
		double expense = valueOfSupply*expenseRate;
		double income = valueOfSupply-expense;
		
		double dividend1;
		double dividend2;
		double dividend3;

		if(income>10000.0) {
		dividend1 = income*0.5;
		dividend2 = income*0.3;
		dividend3 = income*0.2;
		} else {
			dividend1 = income*1.0;
			dividend2 = income*0;
			dividend3 = income*0;
		}
        
		System.out.println("Value of supply: "+valueOfSupply);
		System.out.println("VAT: "+vat);
		System.out.println("Total: "+total);
		System.out.println("Expense: "+expense);
		System.out.println("Income: "+income);
		System.out.println("Dividend 1: "+dividend1);
		System.out.println("Dividend 2: "+dividend2);
		System.out.println("Dividend 3: "+dividend3);
	}
}

- 반복문 *double[] dividendRates=new double[3]

public class AccountingArrayApp {
	public static void main(String[] args) {
		
		double valueOfSupply = Double.parseDouble(args[0]);
		double vatRate = 0.1;
		double expenseRate = 0.3;
		double vat = valueOfSupply*vatRate;
		double total = valueOfSupply+vat;
		double expense = valueOfSupply*expenseRate;
		double income = valueOfSupply-expense;
		
		System.out.println("Value of supply: "+valueOfSupply);
		System.out.println("VAT: "+vat);
		System.out.println("Total: "+total);
		System.out.println("Expense: "+expense);
		System.out.println("Income: "+income);
		
		double[] dividendRates=new double[3];
		dividendRates[0]=0.5;
		dividendRates[1]=0.3;
		dividendRates[2]=0.2;
		
		double dividend1 = income*dividendRates[0];
		double dividend2 = income*dividendRates[1];
		double dividend3 = income*dividendRates[2];
		
		int i=0;
		while(i<dividendRates.length) {
		System.out.println("Dividend: "+(income*dividendRates[i]));
		i=i+1;
	}
  }
}

- 메소드&클래스로 정리

class Accounting{
	public static double valueOfSupply;
	public static double vatRate;
	public static double expenseRate;
	
	public static void print() {
		System.out.println("Value of supply: "+valueOfSupply);
		System.out.println("VAT: "+getVAT());
		System.out.println("Total: "+getTotal());
		System.out.println("Expense: "+getExpense());
		System.out.println("Income: "+getIncome());
		System.out.println("Dividend 1: "+getDividend1());
		System.out.println("Dividend 2: "+getDividend2());
		System.out.println("Dividend 3: "+getDividend3());
	}

	public static double getDividend1() {
		double dividend1 = getIncome()*0.5;
		return dividend1;
	}
	
	public static double getDividend2() {
		double dividend1 = getIncome()*0.3;
		return dividend1;
	}
	
	public static double getDividend3() {
		double dividend1 = getIncome()*0.2;
		return dividend1;
	}

	public static double getIncome() {
		double income = valueOfSupply-getExpense();
		return income;
	}

	public static double getExpense() {
		double expense = valueOfSupply*expenseRate;
		return expense;
	}

	public static double getTotal() {
		double total = valueOfSupply+getVAT();
		return total;
	}

	public static double getVAT() {
		return valueOfSupply*vatRate;
	}
}

public class AccountingClassApp {
	public static void main(String[] args) {	
		Accounting.valueOfSupply=10000.0;
		Accounting.vatRate = 0.1;
		Accounting.expenseRate = 0.3;
		Accounting.print();
	}
}

- 인스턴스: 예를 들어 '가수' 클래스가 있다면 그 인스턴스로 '아이유', '김범수' 등을 만들 수 있다.  '가수' 클래스가 '노래하기' '안무하기' 등의 메서드를 가지고 있다면 '아이유'와 '김범수' 인스턴스는 모두 '노래하기' '안무하기' 메서드를 실행할 수 있다. 새 가수를 추가해야 한다고 해서 다시 '가수' 클래스를 만들 필요는 없고, '박효신'이라는 인스턴스를 만들면 된다.

class Accounting{
	public double valueOfSupply;
	public double vatRate;
	public double expenseRate;
	
	public void print() {
		System.out.println("Value of supply: "+valueOfSupply);
		System.out.println("VAT: "+getVAT());
		System.out.println("Total: "+getTotal());
		System.out.println("Expense: "+getExpense());
		System.out.println("Income: "+getIncome());
		System.out.println("Dividend 1: "+getDividend1());
		System.out.println("Dividend 2: "+getDividend2());
		System.out.println("Dividend 3: "+getDividend3());
	}

	public double getDividend1() {
		double dividend1 = getIncome()*0.5;
		return dividend1;
	}
	
	public double getDividend2() {
		double dividend1 = getIncome()*0.3;
		return dividend1;
	}
	
	public double getDividend3() {
		double dividend1 = getIncome()*0.2;
		return dividend1;
	}

	public double getIncome() {
		double income = valueOfSupply-getExpense();
		return income;
	}

	public double getExpense() {
		double expense = valueOfSupply*expenseRate;
		return expense;
	}

	public double getTotal() {
		double total = valueOfSupply+getVAT();
		return total;
	}

	public double getVAT() {
		return valueOfSupply*vatRate;
	}
}

public class AccountingClassApp {
	public static void main(String[] args) {	
	
		//new를 붙여서 생성한 것이 instance
		Accounting a1=new Accounting();
		a1.valueOfSupply=10000.0;
		a1.vatRate=0.1;
		a1.expenseRate=0.3;
		a1.print();
		
		Accounting a2=new Accounting();
		a2.valueOfSupply=20000.0;
		a2.vatRate=0.05;
		a2.expenseRate=0.2;
		a2.print();
	}
}

 

2023-01-19 수강 완료.

 

쉽게 배우는 자바1 강의는 파이썬 문법을 이미 배운 나에게는 쉬웠다. 전에 배웠던 것을 복습하면서 자바 문법을 적용시키는 느낌으로 강의를 들었다. 다만 파이썬 공부할 때도 클래스/메소드/인스턴스 개념은 어려웠기 때문에 자바1 강의 막바지에 나오는 클래스/메소드/인스턴스는 여전히 어려웠다. 아마 사람들이 가장 힘들어하는 파트이지 않을까 싶다. 쉽게 배우는 자바2에서 더 자세하게 알려주는 것 같아서 자바1 강의보다 천천히, 꼼꼼히 볼 예정이다. 2월 초까지 자바 문법 완성하고 남은 방학 동안 SQLD 자격증 공부해야한다. 화이륑.