

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 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 資料表。在指令碼的開頭，使用者會新增提示來新增 DynamoDB Java程式庫，以協助為 Amazon Q Developer 提供額外的內容。

輸入:

```
// 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)。