

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Java 예제
<a name="examples-java"></a>

다음 Java 예제에서는 사용자가 인라인 코드 제안 생성을 시작하는 방법을 보여줍니다. 이 예제에서는 자체 프로젝트에 대해 코딩 도우미를 트리거하는 방법을 보여줍니다. 다음 예제의 대부분은 다른 언어에 적용됩니다.
+ [클래스 및 함수 생성](#classes-java)
+ [문서 코드](#code-java)
+ [알고리즘 생성](#algorithms-java)
+ [단위 테스트 생성](#tests-java)

## 클래스 및 함수 생성
<a name="classes-java"></a>

전체 또는 부분 클래스 구현을 생성하려면 코드 설명을 사용합니다. 주석은 클래스의 의도를 설명합니다. 간단히 시작하고 필요한 경우 세부 정보를 추가합니다. 클래스를 생성한 후 해당 스켈레톤 내에서 함수를 계속 생성할 수 있습니다.

주석을 작성할 때는 언어의 주석 구조를 사용하는 것이 좋습니다. 에서 Java이는 입니다`/** */`*.*

입력: 

```
/**
 * DocumentReader class. has a name, children and optional parent. 
 * Includes I/O functions to read and
 * write document
 */
```

출력: 

```
/**
 * DocumentReader class. has a name, children and optional parent. 
 * Includes I/O functions to read and
 * write document
 */
import java.util.ArrayList;
public class DocumentReader {
    private String name;
    private DocumentReader parent;
    private ArrayList<DocumentReader> children;

    /**
     * Constructor
     * @param name name of the document
     * @param parent parent of the document
     */
    public DocumentReader(String name, DocumentReader parent) {
        this.name = name;
        this.parent = parent;
        this.children = new ArrayList<>();
    }

    /**
     * Constructor
     * @param name name of the document
     */
    public DocumentReader(String name) {
        this(name, null);
    }
    /**
     * Getter for name
     * @return name of the document
     */
    public String getName() {
        return name;
    }

    /**
     * Getter for parent
     * @return parent of the document
     */
    public DocumentReader getParent() {
        return parent;
    }

    /**
     * Getter for children
     * @return children of the document
     */
    public ArrayList<DocumentReader> getChildren() {
        return children;
    }

    /**
     * Adds a child to the document
     * @param child child to be added
     */
    public void addChild(DocumentReader child) {
        children.add(child);
    }

    /**
     * Removes a child from the document
     * @param child child to be removed
     */
    public void removeChild(DocumentReader child) {
        children.remove(child);
    }
}
```

이제 초기 클래스가 있으므로 추가 설명과 함께 추가 함수를 생성할 수 있습니다.

입력:

```
/**
* function to read document from local directory path
* and print first line of document
*/
```

출력:

```
/**
 * function to read document from local directory path
 * and print first line of document
 */
public void readDocument() {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(name));
        String line = reader.readLine();
        System.out.println(line);
        reader.close();
    } catch (IOException e) {
        System.out.println("Error reading document: " + e.getMessage());
    }
}
```

## 문서 코드
<a name="code-java"></a>

인라인 설명서에 의존하여 코드 문서의 시간을 단축합니다. Java 설명 나누기을 추가합니다`/* */`.

입력: 

```
import java.util.function.Function;

public class S3Utils {
    /* 
     * <place cursor here>
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

인라인 생성이 발생하지 않는 경우 문서를 원하는 위치에 커서를 배치한 후 Amazon Q Developer 인라인 제안을 실행합니다.

출력:

```
import java.util.function.Function;

public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

코드(클래스, 함수 또는 스크립트 요소)에 대한 더 간단한 설명을 보려면 설명서를 추가하려는 코드 섹션 앞에 전략적으로 배치된 문자(`//`)를 사용합니다.

입력:

```
// 
public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

출력:

```
// This class is used to generate a function that returns the S3 URL for a given key
public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

## 알고리즘 생성
<a name="algorithms-java"></a>

Amazon Q Developer는 특히 AWS SDKs. 스크립트에 원하는 함수를 지정하는 프롬프트를 추가합니다.

이 예제에서는 이름 값에 대한 사용자 ID 키의 해시 맵을 생성한 다음 버블 정렬 알고리즘을 사용하여 정렬 함수를 생성합니다.

입력:

```
import java.util.HashMap;
public class SortList {

    // generate key value pair hash map for 
    // user id and name
    public static HashMap<Integer, String> getUserIdNameMap() {
        HashMap<Integer, String> userIdNameMap = new HashMap<Integer, String>();
        userIdNameMap.put(1, "Amit");
        userIdNameMap.put(2, "Rahul");
        userIdNameMap.put(3, "Vijay");
        userIdNameMap.put(4, "Raj");
        userIdNameMap.put(5, "Kumar");
        return userIdNameMap;
    }

    /*
    * Create function to sort UserIdName map by name alphabetically using bubble sort
    */ 
    
    
}
```

출력:

```
/*
* Create function to sort UserIdName map by name alphabetically using bubble sort
*/ 
public static HashMap<Integer, String> sortUserIdNameMap(HashMap<Integer, String> userIdNameMap) {
    int size = userIdNameMap.size();
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (userIdNameMap.get(i).compareTo(userIdNameMap.get(j)) > 0) {
                String temp = userIdNameMap.get(i);
                userIdNameMap.put(i, userIdNameMap.get(j));
                userIdNameMap.put(j, temp);
            }
        }
    }
    return userIdNameMap;
}
```

또한 사용자는 표준 절차에 대한 프롬프트를 생성할 수 있습니다. 이 예제에서 사용자는 해시 맵을 Amazon DynamoDB 테이블에 저장하는 프롬프트를 생성합니다. 스크립트 시작 부분에 사용자는 Amazon Q Developer에 추가 컨텍스트를 제공하는 데 도움이 되는 DynamoDB Java 라이브러리를 추가하라는 프롬프트를 추가합니다.

입력:

```
// add libraries for Amazon DynamoDB
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

     /*
     * Store sorted UserIdName map into Amazon DynamoDB table named users
     */
```

출력:

```
// add libraries for Amazon DynamoDB
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

     /*
     * Store sorted UserIdName map into Amazon DynamoDB table named users
     */
    public static void storeSortedUserIdNameMap(HashMap<Integer, String> userIdNameMap) {
        // create Amazon DynamoDB client
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();

        // store sorted UserIdName map into Amazon DynamoDB table named users
        for (int userId : userIdNameMap.keySet()) {
            String name = userIdNameMap.get(userId);
            client.putItem("users", new HashMap<String, Object>() {{
                put("userId", userId);
                put("name", name);
            }});
        }
    }
```

## 단위 테스트 생성
<a name="tests-java"></a>

인라인 설명을 통해 Amazon Q Developer는 단위 테스트를 생성하여 어설션 및 기타 JUnit 테스트를 수행할 수 있습니다. 이 예제에서 사용자는 먼저 Amazon Q에 JUnit용 해당 라이브러리를 생성하여 테스트 스크립트의 컨텍스트를 설정하도록 요청합니다. 그런 다음 사용자는 퍼블릭 클래스와 선언자 및 설명 문자열을 차례로 생성합니다.

입력:

```
// import libraries for java unit tests
import org.junit.Test;
import static org.junit.Assert.*;

public class UnitTests {

    @Test 
    /*
     * Create unit test for getUserIdNameMap
     */  
}
```

출력:

```
@Test 
/*
* Create unit test for getUserIdNameMap
*/
public void testGetUserIdNameMap() {
    // create a new instance of the UserIdNameMap class
    UserIdNameMap userIdNameMap = new UserIdNameMap();

    // create a new instance of the User class
    User user = new User("John", "Doe");

    // add the user to the map
    userIdNameMap.addUser(user);

    // get the user from the map
    User retrievedUser = userIdNameMap.getUser("John");

    // assert that the retrieved user is the same as the user added to the map
    assertEquals(user, retrievedUser);
}
```

또한 사용자와 Amazon Q Developer 간의 채팅에서 사용자의 코드 입력 프롬프트를 기반으로 단위 테스트를 제안하고 생성합니다. 자세한 내용은 [채팅 예제](examples-chat.md)를 참조하세요.