

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

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

Os seguintes exemplos de Java exemplos demonstram como os usuários podem começar a gerar sugestões de código em linha. Esses exemplos ilustrativos mostram como acionar o assistente de codificação para seus próprios projetos. A maioria dos exemplos a seguir se aplica a outros idiomas: 
+ [Gere classes e funções](#classes-java)
+ [Código do documento](#code-java)
+ [Gere algoritmos](#algorithms-java)
+ [Gere testes unitários](#tests-java)

## Gere classes e funções
<a name="classes-java"></a>

Para gerar a implementação total ou parcial da classe, use comentários de código. O comentário descreve a intenção da turma. Comece de forma simples e adicione mais detalhes, se necessário. Depois de gerar uma classe, você pode continuar gerando funções dentro de seu esqueleto. 

Ao escrever comentários, é preferível usar a estrutura de comentários do idioma. Em Java, isso é `/** */`*.* 

Entrada: 

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

Saída: 

```
/**
 * 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);
    }
}
```

Agora que há uma classe inicial, uma função adicional pode ser gerada com comentários adicionais. 

Entrada:

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

Saída:

```
/**
 * 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());
    }
}
```

## Código do documento
<a name="code-java"></a>

Reduza o tempo na documentação do código confiando na documentação em linha. Adicione um Java pausa para comentários`/* */`.

Entrada: 

```
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;
        };
    }
}
```

Se a geração em linha não ocorrer, execute uma sugestão em linha do Amazon Q Developer depois de colocar o cursor onde você deseja a documentação.

Saída:

```
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;
        };
    }
}
```

Para explicações mais simples do código (classes, funções ou elementos de script), use caracteres de encaminhamento (`//`) que estão estrategicamente colocados antes das seções de código nas quais você deseja adicionar documentação. 

Entrada:

```
// 
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;
        };
    }
}
```

Saída:

```
// 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;
        };
    }
}
```

## Gere algoritmos
<a name="algorithms-java"></a>

O Amazon Q Developer pode gerar algoritmos populares, especialmente relacionados AWS SDKs a. Em seu script, adicione um prompt que especifique a função que você deseja. 

Este exemplo gera um mapa de hash das chaves de identificação do usuário para nomear valores e, em seguida, gera uma função de classificação usando o algoritmo de classificação por bolhas.

Entrada:

```
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
    */ 
    
    
}
```

Saída:

```
/*
* 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;
}
```

Além disso, os usuários podem criar solicitações para procedimentos padrão. Neste exemplo, o usuário cria um prompt para armazenar o mapa de hash em uma tabela do Amazon DynamoDB. No início do script, o usuário adiciona um prompt para adicionar o DynamoDB Java bibliotecas para ajudar a fornecer contexto adicional ao Amazon Q Developer.

Entrada:

```
// 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
     */
```

Saída:

```
// 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);
            }});
        }
    }
```

## Gere testes unitários
<a name="tests-java"></a>

Com comentários em linha, o Amazon Q Developer pode gerar testes unitários para realizar afirmações e outros JUnit testes. Neste exemplo, o usuário primeiro solicita à Amazon Q que gere bibliotecas aplicáveis JUnit para definir o contexto do script de teste. Em seguida, o usuário cria uma classe pública seguida por um declarador e sequências de comentários.

Entrada:

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

public class UnitTests {

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

Saída:

```
@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);
}
```

Além disso, em um bate-papo entre o usuário e o Amazon Q Developer, ele sugere e gera testes unitários com base nos prompts de entrada de código do usuário. Para obter mais informações, consulte [Exemplos de bate-papo](examples-chat.md).