Intro to Java_Functional Programming (Udacity)

치즈말랑이·2021년 9월 19일
0

Lesson 1_Variables and Data Types

자바는 파이썬과는 다르게 문장 끝에 ;를 붙여야 하고,
문법들도 조금씩 다 다르다. 숫자형 앞에는 무조건 int를, 문자열 앞에는 String을 붙여야한다.

String driverFirstNAme;
driverFirstName = "Hamish";
String driverLastName;
driverLastName = "Blake";
String driverFullName = driverFirstNAme + driverLastName;
System.out.println(driveFullName);
Print output:
HamishBlake
  • extra 넣는법
String driverFullName = driverFirstNAme + " " + driverLastName;
Print output:
Hamish Blake

int stops;
int fare;
stops = 0;
fare = 0;
stops = stops + 1;
fare = fare + 5;
stops = stops + 1;
fare = fare + 3;
stops = stops + 1;
fare = fare + 7;
System.out.println(stops);
System.out.println(fare);
Print output:
3
15

int stops;
int fare;
stops = 0;
fare = 0;
stops = stops + 1;
fare = fare + 5;
stops = stops + 1;
fare = fare + 3;
stops = stops + 1;
fare = fare + 7;
System.out.println(stops);
System.out.println(fare);
System.out.println("The bus made $"+fare+" after "+stops+" stops ");

The bus made $, after, stops : string literal
fare, stops : variable

String language = "java"; // 좌변 : Declaring, 우변 : Initializing
String feeling = "Love";
feeling = feeling.toLoswerCase();
language = languae.toUpperCase();
System.out.println("I " + feeling + " " + language);
Print output:
I love JAVA

driverFirstName 에서 F와 N 처럼 대문자로 표기되어 있는것을 camel case라고 한다. (낙타 혹 같이생겨서)
d처럼 소문자로 된것을 loswer camel case라고 한다.
variable을 쓸 때 맨앞은 무조건 소문자로 쓰는데 그 뒤에 다른 단어를 합쳐서 쓸 때에는 보기 편하게 시작 알파벳을 대문자로 한다.

Variable Name Rules
(1) variable names are case sensitive (대,소문자 구분)
(2) start variable names with a letter (variable 시작할 땐 무조건 숫자가아니고 문자로 시작)
(3) cannot have white spaces (variable에 띄어쓰기 안됨)

Variable Types (numbers)
(1) Integer : 10-digit number로 되어 있어서 다른 언어보다 빠르게 run 할 수 있다. negative number 가능

int maxInt = 2147483647;

(2) long : Integer보다 좀 느리다. negative number 가능

muchMore = 2147483647*10000000;

(3) Double : fractional number (소수) 가능, long보다 느리다.

double fraction = 99.275;

Variable Types (text)
(1) String : quotation mark 사용

String fullText = "(b) WWII ended 1945";

(2) Character : single letter 사용 가능

char answer = 'b';
char three = '3';
char ten = '10'; -> 안됨

Variable Types (decision)
(1) Boolean

boolean fact = true;
boolean condition = false;
  • Data Types Quiz
    Whic of these statements is wrong?
    Select all statements where the declaration type does NOT match the value !
  1. char me = 'I';
  2. boolean fact = true;
  3. boolean number = 17; -> wrong
  4. String text = "text";
  5. double price = 23.75;
  6. long total = 100.1; -> wrong

Variable Arithmetic
(1) Addition

int x = 2+3;

(2) Subtraction

int y = 4-5;
int temp = -20;

(3) Multiplication : *(asterisk sign)

int days = 7*4;

(4) Division

double div = 5/2;

double을 써도 integer인 5와 2를 나누는거라서 결과값이 2.5가아니라 2다. 소수점 이하는 버림.
-> 해결방법 : 나누는 수에 소수점을 붙여준다.

double accurate = 5/2.0;

Truncation
Cutting off the digits to the right of a decimal point.

double div = 5/2; = 2 ≠ 2.5

Casting

double current = 17;
double rate = 1.5;
double future = current * rate;
System.out.println(future); = 25.5
int approx = (int) future; 
System.out.println(approx); = 25

우변의 (int)는 Java에게 int로 바꾸고싶다고 알려주는 것. 이 part를 casting이라고 한다.
This part here is called casting because we basically casted or molded this value of the future variable to become an integer

int x = 5;
int y = 2;
double div = x/y;
System.out.println(div); = 2
double accurate = (double)x/y;
System.out.println(accurate); = 2.5

Multiline Comments
파이썬에서 주석 역할을 하는 #가 자바에서는 //이다.
여러문장을 쓰고 싶으면

/*
하고싶은 말
*/

하면 된다.

  • Quiz : Calculate the average
    Average Grade: The total sum of grades divided by the number of subjects graded
/* Your friend seems to be really good at music,
he managed to score 96% on his final exam !
Now that you know all 5 subject grades,
update the average calculation below to calculate the total average of all 5 subjects. */

double maths = 97.5;
double english = 98;
double science = 83.5
double drama = 75;
double sum = maths + english + science + drama;
double average = sum / 4;
System.out.println(average);
  • Quiz : What do you think this program will print out?
int x = 0;
int y = 4;
double z = 3;
x = x + 2;
z = x + y - 7;
y = x * 3;
System.out.println("x = "+x);
System.out.println("y = "+y);
System.out.println("z = "+z);

x = 2
y = 6
z = -1.0

Lesson 2_Control Flow and Conditionals

사람은 날씨가 추운가? 라는 질문에 true 이면 코트를 입는다
컴퓨터에 적용시키면

boolean isCold;

if(isCold) {
	//executes ONLY if isCold is true
    System.out.println("It's cold, wear a coat!");

isCold : Test condition (Value varies Between true and false)
Booleans : Always true or false Great for decision-making

{ } 내용 : block of code

Self-Driving Car를 예로 들어보자.
Is the light green?
-> If yes, then drive

boolean isLightGreen;

if(isLightGreen) {
	// traffic light is green
    System.out.println("DRive!");
}
if(test2){
···
}

Variable Scope
block or range of code where a certain variable can be used and referred to.

boolean isLightGreen;

if(isLightGreen) {
	// traffic light is green
    System.out.println("DRive!");
}

이 전체가 isLightGreen scope 이다.

boolean isLightGreen;

if(isLightGreen) {
	// traffic light is green
    double carSpeed = 100; //in km/hr
    System.out.println("Drive!");
    System.out.println("Speed is: " + carSpeed);
}

여기서는 전체가 isLightGreen scope이고,
//traffic부터 "Speed is : " + carSpeed); 까지가 carSpeed scope이다.
만약에 if 문의 {} 밖에 carSpeed = carSpeed - 10; 을 쓴다면,
carSpeed scope 밖에 있으므로 에러가 뜰 것이다. access 불가.

scope : A set of curly braces defines a variable scope

파이썬에서는 elif인데 자바에서는 else if 라고 한다.

boolean isLightGreen
boolean isLightYellow

if(isLightGreen) {
	//traffic light is green
    System.out.println("Drive!");
} else if(isLightYellow) {
	//light is NOT green but is yellow
    System.out.println("Slow down.");
} else{
	//light is neither green nor yellow
    System.out.println("Stop.");
}

Boolean Expressions
Booleans are true or false
Values can be directly assigned ...
boolean b1 = true;
boolean b2 = false;
or calculated with tests like comparions!
boolean b3 = 3 < 5; // value -> true
boolean b4 = 3 > 5; // value -> false

int x = 10; 이라고 선언한 후
Expression Value
x == 9 -> false
x = 9 -> no boolean value
=는 variable assignment 이기 때문

Logical Operators
Three main logical operators:
1) AND && : 3 < 5 && 2 > 15 -> false
2) OR || : 3 < 5 || 2 > 15 -> true
3) NOT ! : !(3 < 5) -> false
-> turns a value into its opposite

if(age <= 15 || age > 60 || isStudent){
···
}

More Logical Operators
Using multiple logical operators
&& will evaluate first, then ||
false && true || true -> true
false && (true || true) -> false

Quiz.

'a' == 'a' || false || 10 >50 -> true
true && 3 > 5 -> false
true && (3 > 5 || 2 < 10) -> true
!(10 > 1) -> false

Quiz.

int rating = 4;
if (rating >= 0 && rating <= 5) {
	// rating is 0-5
    if (rating <= 2) {
    	// rating is less than or equl to 2
    	System.out.println("What's the reason for your low rating?");
    }
    System.out.println("Thank you for your feedback.");
}

Switch Statement

int passcode = 555;
STring coffeType;
if (passcode == 555) {
	//espresso passcode
    coffeeType = "Espresso";
} else if (passcode == 312) {
	//vanilla passcode
    coffeType = "Vanilla latte";
} else if (passcode == 629) {
	//drip coffee code
    coffeeType = "Drip coffee";
} else{
	//unknown passcode
    coffeeType = "Unknown";
}
System.out.println(coffeeType);

스위치를 사용하면 더 간단하게 표현할 수 있다.

int passcode = 555;
String coffeeType;
switch(passcode) {
	case 555: 
    		coffeeType = "Espresso";
		break;
	case 312: 
    		coffeeType = "Vanilla latte";
		break;
	case 629: 
    		coffeeType = "Drip coffee";
		break;
	default : 
    		coffeeType = "Unknown";
		break;
}
System.out.println(coffeeType);

Lesson3_Functions

Functions : Group this code and Reuse it
Organize and group code, Perform a specific task
println : function
System.out.println("Print this")
System.out.println("Then this")
System.out.println("And this!")
각각은 function call(함수 호출)이다.

Function definition

  • Contains the code a function executes
  • Calling a function is equivalent to executing the code in the definition
public void println(String x) {
	// check that the String exists
    if )x == null) {
    	x = "null";
    }
    try {
    	ensureOpen();
        // write String to screen
        textOut.write(x);
    } catch(IOException e) {
    	trouble = true;
        
    }
    newLine();

Don't need to know the details of the println() definition!

Quiz.
Which scenarios would be helped by organizing the described code into functions?
1. Code that adds two numbers together that you want to use repeatedly to keep track of expenses.
-> Functions let you easily reuse code.
2. A friend wants to share restaurant rating code with you.
-> Organize and group code
3. You use alarm setting code in multiple clocks, but the code has a mistake in it that you need to fix.
-> More maintainable code

노래방 기계에서 가사가 반복해서 나올때

public void chorus() {
	// print out 4 lines of chorus
    System.out.println("Once I had a love and it was a gas");
    System.out.println("Soon turned out had a heart of glass");
    System.out.println("Seemed like the real thing, only to find");
    System.out.println("Mucho mistrust, love's gone behind");
}

public : access modifier, anyone can use public functions
자바 함수는 항상 public 이나 private로 시작한다. 이것을 access modifier라고 부른다.
void : return type. 어떤 데이터로도 되돌아가지 않는다.
function name : how we call our function

chorus();

Prompt this code to run by calling the function

Function definition : 함수 정의할 때 구체적으로 써줘야 한다.
detailed code
How to use the function
If it returns data

Funciton call : 함수 호출할 때 그냥 chorus();만 적어주면 된다.
Use function in separate program.
refer to it by name

Parameters and Arguments

  • Parameters
    Variables in the parentheses of our function, that we can then use inside our function
public void greeting(String location) {
	// greet a specific location
    System.out.println("Hello, " + location);
}

Function call: greeting ("New York");
Print output: Hello, New York

Quiz. What will this print for the following calls?

public void weatherInterpreter(int temperature) {
	if (temperature > 30) {
    	System.out.println("It's hot outside!");
    } else if (temperature < 5) {
    	System.out.println("Brr, consider wearing a jacket.");
    } else {
    	System.out.println("Not too hot, not too cold");
    }
}

Function calls Print output
weatherInterpreter(4); -> Brr, consider wearing a jacket.
weatherInterpreter(32); -> It's hot outside!

int degreesC = 32;
weatherInterpreter(degreesC);
Use variables : Easy to change variable values. Input the correct type of variable.

Multiple Parameters

  • Function definition
public void printPhoto (int width, int height, boolean inColor) {
	System.out.println("Width = " + width + " cm");
    System.out.println("Height = " + height + " cm");
    if(inColor) {
    	System.out.println("Print is full color.");
    } else {
    	System.out.println("Print is black and white.");
    }
}

Function call : printPhoto(30, 40, true);
Print output :
Width = 30cm
Height = 40cm
Print is full color.

Argument Order

Function call
printPhoto(30, 40, true); ≠ printPhoto(40, 30, true);
order과 type은 매우 중요하다.

Quiz. Write a valid function call for the funcion likePhoto?

public void likePhoto(int currentLikes, String comment, boolean like) {
	//prints out comment and who is commenting
    System.out.println("Feedback: " + comment);
    if(like) {
    	// increase number of likes by 1
        currentLikes = current:ikes + 1;
    }
    System.out.println("Number of likes: " + currentLikes);
}

Wirte the function call here: ex) likePhoto(10,"great photo!", true);
argument 하나라도 빼먹으면 에러남.

Return Values
Input : Parameters
-> Function ->
Output : Return value

void : not returning any data

예를들어

public void functionName() {
	// internal block of code
}

이것을 return하고 싶으면 void를 빼고

public String functionName() {
	// internal block of code
}

이렇게 쓰면 String value를 return한다. int나 boolean도 가능.
print 함수는 단지 우리 눈에만 보여주고 그 뒤에 나오는 함수들과는 관련이 없기때문에
return과 print함수는 다르다.

Tracking Photo Likes

public void likePhoto(int currentLikes, String comment, boolean like) {
	//prints out comment and who is commenting
    System.out.println("Feedback: " + comment);
    if(like) {
    	// increase number of likes by 1
        currentLikes = current:ikes + 1;
    }
    System.out.println("Number of likes: " + currentLikes); // 여기서 currentLikes가 return value
}

처음에는 좋아요를 눌렀으나 시간이 지나서 좋아요를 취소한 사람을 생각해보자.
그러면 누적된 currentLikes가 하나 줄어야 하는데 이 때 return value를 사용해야 한다.
currentLikes can only be reached inside our definition!
Need to output the value of currentLikes

To return a value you need :
1) a return type - void, int, String, etc.
2) a return statement - line of code that returns a value

public int likePhoto(int currentLikes, String comment, boolean like) {
	//prints out comment and who is commenting
    System.out.println("Feedback: " + comment);
    if(like) {
    	// increase number of likes by 1
        currentLikes = current:ikes + 1;
    }
    //print out current number of likes
    System.out.println("Number of likes: " + currentLikes); // 여기서 currentLikes가 return value
    //return current likes
    return currentLikes;
}
int returnedLikes = likePhoto(0, "Nice color!", true);
int totalLikes = likePhoto(returnedLikes, "I like this", true);
likePhoto(returnedLikes, "I like this", true);

Return values let you use values in other function calls or programs!

Cashier Program

Quiz. Making Change
Write a function that returns the correct change.
makeChange(double itemCost, double dollarProvided)

Function definition

public double makeChange(double itemCost, double dollarsProvided) {
	// calculate change
    // change is dollars - item cost
    double change = dollarsProvided - itemCost;
    return change;

Returning Random Numbers

Math.random();

Returns a random decimal value between 0 and 1
Range includes 0 but not 1

//random num between 0 and (almost) 1
double randomNumber = Math.random();

//random num between 0 and (almost) 10
double randomNumber = Math.random() * 10;

// cast to integer (ignore decimal part)
// ex. 9.985 becomes 9
int randomInt = (int) randomNumber;

Casting : Turning one variable type into another

Rolling Dice

public int rollDice() {
	// random num between 0 and (almost) 1
    double randomNumber = Math.random();
    
    // change range to 0 to (almost) 6
    randomNumber = randomNumber * 6;
    
    // shift range up one
    randomNumber = randomNumber + 1;
    
    // cast to integer (ignore decimal part)
    // ex. 6.998 becomes 6
    int randomInt = (int) randomNumber ;
	// return statement
    return randomInt;
}

Function calls

int roll1 = rollDice();
int roll2 = rollDice();
System.out.println("Roll 1: " + roll1);
System.out.println("Roll 2: " + roll2);

Java Documentation
Documentation
Lets you find out about built-in functions Programmers use it all the time!

  • function descriptions
  • variable types
  • how to use

Java Comments
Help people understand your code
Single-line comments
// single line comment
// quick note to self or description

Multiline comments
/
내용
/

Java Documentation(doc) comments

/**
 * General description of a function.
 *
 * @param a first input parameter, named a
 * @param b second parameter, named b
 *
 * @return description of return value
 */

앞서 작성했던 rollDice의 경우 다음과 같이 작성할 수 있다.

/**
 * This dice funciton simulates a random dice roll
 * for a dice with a given number of sides.
 * 
 * @param sides the number of sides of a dice
 * @return random roll value (an int)
 */

Lesson 4_Loop

Alarm function

public void alarm() {
	boolean on = checkAlarm();
    if(on){
    	beep();
        on = checkAlarm();
    }
    if(on){
    	beep();
        on = checkAlarm();
    }
    if(on){
    	beep();
        on = checkAlarm();
    }
}
    

While Loops
While은 if와 비슷한 함수이다.

while(on){
	beep();
    on = checkAlarm();
}

while 쓰면 true가 그만할때까지 계속 반복

public void alarm(){
	boolean on = checkAlarm();
    while(on){
    	beep();
        on = checkAlarm();
    }
}

Quiz. What's the condition?

글자수가 101이 될때까지 0을 붙이기

String googol = "1";
int len = googol.length();
while(len < 101) {
	googol = googol + "0";
    len = googol.length();
}

yahtzee 게임

  • 2 Dice로 게임을 할 때
public int keepRolling() {
	int dice1 = rollDice();
    int dice2 = rollDice();
    int count = 1;
    while(!(dice1 == dice2)) {
    	//we need to re-roll
        dice1 = rolldice();
        dice2 = rollDice();
        count = count + 1;
    }
    return count;
}

자바에서는 A == B == C 라고 쓰면 에러난다.
두개만 == 가능.
-> A == B && B == C 라고 써야 한다.

  • 3 Dice로 게임을 할 때
public int keepRolling() {
	int dice1 = rollDice();
    int dice2 = rollDice();
    int dice3 = rollDice();
    int count = 1;
    while(!(dice1 == dice2 && dice2 == dice3)) {
    	//we need to re-roll
        dice1 = rolldice();
        dice2 = rollDice();
        dice3 = rollDice();
        count = count + 1;
    }
    return count;
}
  • 5 Dice로 게임을 할 때
public int keepRolling() {
    int dice1 = rollDice();
    int dice2 = rollDice();
    int dice3 = rollDice();
    int dice4 = rollDice();
    int dice5 = rollDice();
    int count = 1;
    while (!(dice1 == dice2 && dice2 == dice3 && dice3 == dice4 && dice4 == dice5)) {
        //we need to re-roll
        dice1 = rollDice();
        dice2 = rollDice();
        dice3 = rollDice();
        dice4 = rollDice();
        dice5 = rollDice();
        count = count + 1;
    }
    return count;
}

- Warning Alert - While loop

public void raiseAlarm (int numOfWarnings) {
	int i = 1; // loop counter
    while (i <= numOfWarnings) { // loop condition
    	System.out.println("Warning");
        i++; // loop increment
    }
}

- Warning Alert - For loop

for(int i = 1; i <= numOfWarnings ; i++){
	System.out.println("Warning");
}

for loop에서는 for() 안에 세가지 요소를 넣어야 하는데
loop counter, loop condition, loop increment를 차례대로 넣어주면 된다.

다른 버전

for(int i = 1; i <= numOfWarnings ; i++){
	System.out.println("Warning # " + i);
}

Quiz. Counting the blocks
1
4
9
이런식으로 블럭을 쌓을 때 층에 따른 전체 블럭의 개수

11+22+3*3=14

public int countBlocks(int levels){
	int total = 0; // 초기화를 먼저 시켜줘야 한다.
    for(int i=1; i<=levels; i++){
    	total = total + (i*i);
    }
    return total;
}
  • Loop counters
/**
 * Adds the numbers 15 + 16 + .. + 20
 * @return the total sum
 */
public int addNumbers() {
	int sum = 0;
    for (int i = 15; i<=20; i++){
    	sum = sum + i;
    }
    return sum;
}

i--는 decrement로 i++와는 반대로 하나씩 뺀다. (i=i-1)

i=i+1; : i++;
i=i-1; : i--;
i=i+5; : i+=5;
i=i-6; : i-=6;
i=i3; : i=3;
i=i/2; : i/=2;

/**
 * Print the even numbers between 2 and 10
 */
public void evenNumbers(){
	for (int i = 2; i <= 10; i +=2) {
    	System.out.println(i);
    }
}
  • Wifi Search
/**
 * Wifi search
 */
public void searchWifi(){
	for(int i = 1; i<=10; i++){
    	boolean wifiAvailable = checkWifi();
        if (wifiAvailable){
        	System.out.println("Wifi found");
            break;
        }
    }
}
  • Roll a six
/**
 * Rolls a dice till you get a 6 then you win
 * but if you get a 3 you lose
 */
public boolean rollAsix(){
	int dice = rollDice();
    while(dice!=6){
    	dice = rollDice();
        if(dice == 3)
        	break;
    }
    if(dice == 6)
    	return true;
    else
    	return false;
}
  • Martingale strategy
public int martingale() {
	int money = 1000;
    int target = 1200;
    int bet = 10;
    while(money>bet){
    	boolean win = play();
        if(win){
        	money += bet;
            bet = 10;
        }
        elseP
        	money -= bet;
            bet *= 2;
        }
    }
    return money;
}

return money가 while문 밖에 있는데 .. 원리 이해가 잘 안된다.

profile
공부일기

0개의 댓글