sm 기술 블로그

절차지향 (메소드/입력과 출력/문자열) 본문

Java

절차지향 (메소드/입력과 출력/문자열)

sm_hope 2022. 4. 14. 10:59
메소드

메소드는 임 정의된 것을 재사용함으로써 재활용, 코드량 감소, 유지보수유리의 장점을 가지고 있다.

 

 

메소드의 정의와 호출

메소드를 만드는 것을 정의(define), 메소드를 실행하는 것을 호출(call) 라고 한다.

 

public class MethodDemo1 {
    public static void numbering() { //메소드의 정의
        int i = 0;
        while (i < 10) {
            System.out.println(i);
            i++;
        }
    }
 
    public static void main(String[] args) {
        numbering(); //메소드의 호출
    }
}

//중괄호를 통해 메소드의 호출, 정의를 할 수 있음.
//출력 결과
0
1
2
3
4
5
6
7
8
9

 

main

하고자 하는 작업을 메인에서 실행되도록 자바와 개발자 사이에 맺어진 약속이다. (약속은 기억해야 하는 부분이다.)

 

 

입력과 출력

 

입력값 : 메개변수와 인자를 통해서 도달할 수 있다.

 

public class MethodDemo4 {
    public static void numbering(int limit) { /* limit라는 변수를 통해서 메인에서 받은 5를 전달 받을 수 있다.
    						 int limit는 매개변수이다. */
        int i = 0;								
        while (i < limit) {
            System.out.println(i);
            i++;
        }
    }
 
    public static void main(String[] args) {
        numbering(5); //메소드에 5의 입력값을 주고 있다. (5는 인자이다)
    }
}

인자와 매개변수는 여러개를 배치할 수 있다.

두개의 매개변소와 인자의 관계

 

return

 

※ 메소드의 입력, 출력을 먼저 보면 어떤 용도고 어떻게 동작하는지 빠르게 알 수 있다. (전체적인 맥락을 먼저 보는것)

public class MethodDemo6 {
    public static String numbering(int init, int limit) {
        int i = init;
        // 만들어지는 숫자들을 output이라는 변수에 담기 위해서 변수에 빈 값을 주었다.
        String output = "";
        while (i < limit) {
            // 숫자를 화면에 출력하는 대신 변수 output에 담았다.
            output += i;
            i++;
        }
        // 중요!!! output에 담겨 있는 문자열을 메소드 외부로 반환하려면 아래와 같이 return 키워드 뒤에 반환하려는 값을
        // 배치하면 된다.
        return output;
    }
 
    public static void main(String[] args) {
        // 메소드 numbering이 리턴한 값이 변수 result에 담긴다.
        String result = numbering(1, 5);
        // 변수 result의 값을 화면에 출력한다.
        System.out.println(result);
    }
}​
//출력결과
1234

public static String numbering(int init, int limit) 에서 String은 number 메소드가 반드시 String으로 반환한다는 뜻.

 

return은 메소드라는 부품의 가치를 높이기 위해서 하는 것이다. 즉, return이 없다면 메소트는 특정작업만 수행하는 응용하지 못하는 반쪽짜리가 되게 된다.

 

retrun을 이용한 텍스트 파일을 만드는 코드

import java.io.*; // 지금은 무시
 
public class MethodDemo7 {
    public static String numbering(int init, int limit) {
        int i = init;
        String output = "";
        while (i < limit) {
            output += i;
            i++;
        }
        return output;
    }
 
    public static void main(String[] args) {
        String result = numbering(1, 5);
        System.out.println(result);
        try { // 지금은 무시
            // 다음 행은 out.txt 라는 파일에 numbering이라는 메소드가 반환한 값을 저장합니다.
            BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"));
            out.write(result);
            out.close();
        } catch (IOException e) {
        } // 지금은 무시
    }
}

만약 배열과 return을 활용한다면.

public class ReturnDemo4 {
 
    public static String[] getMembers() {
        String[] members = { "최진혁", "최유빈", "한이람" };
        return members; //배열로 리턴
    }
 
    public static void main(String[] args) {
        String[] members = getMembers(); //배열로 리턴된 값을 받음
    }
 
}

다음과 같이 한번에 리턴할 수 있다.

 


입력과 출력

 

String[] args

class InputDemo{
    public static void main(String[] args){
        System.out.println(args.length);
    }
}

String은 문자열 []가 있다면 배열을 뜻한다. / args 라는 이름을 가진 변수를 정하는데, 문자열 배열을 맏을 수 있다.

 

args.length는 args 배열의 크기를 알 수 있다.

 

자바에게 입력값을 주는 방법

https://www.youtube.com/watch?v=mXkSqhSviK0&list=PLuHgQVnccGMCeAy-2-llhw3nWoQKUvQck&index=61 

 

argument에 one, two, three를 입력했을때

실행중에 데이터를 입력

 

import java.util.Scanner;
import java.io.*;
 
public class Scanner3Demo {
 
    public static void main(String[] args) {
        try {
            File file = new File("out.txt");
            Scanner sc = new Scanner(file);
            while(sc.hasNextInt()) {
                System.out.println(sc.nextInt()*1000); 
            }
            sc.close();
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }
         
    }
 
}

 

sc라는 변수에 이미 기록되어 있는 out.txt 파일의 기록을 가지고옴.

 

catch : 예외라는 뜻이다. 즉, out.txt 를 찾지 못할 경우 에러를 화면에 띄우라는 뜻.

 

 

Comments