用ChatGPT写了段Java代码,发现它真的懂!

1,629 阅读5分钟

介绍

人工智能已经革命了许多领域,计算机编程也不例外。ChatGPT是一种先进的人工智能模型,可以生成类似于人类的响应文本。近年来,它已被用于生成可以用于自动化重复任务,增加生产力和减少错误的计算机代码。使用ChatGPT可以生成的编程语言之一是Java。在本文中,我们将探讨如何使用ChatGPT编写Java代码,以及所生成代码的review。

Java基础知识

Java是一种面向对象的编程语言,广泛用于开发移动应用程序、网络应用程序和其他软件。Java代码被编译成字节码,可以在安装了Java虚拟机(JVM)的任何计算机上运行。Java以其简单性、可靠性和安全性而闻名。

使用ChatGPT编写Java代码

使用ChatGPT编写Java代码的好处之一是它可以节省大量时间和精力。您可以简单地提供文本提示,让ChatGPT为您生成代码,而不必从头编写代码。这对于刚学习如何在Java中编程的初学者特别有用。

要使用ChatGPT生成Java代码,您需要提供一个文本提示,指定您想要代码完成的任务。例如,如果您想生成将“Hello World”打印到控制台的代码,您可以提供提示:

我的要求: “编写Java代码以将“Hello World”打印到控制台”。

ChatGPT:

当然可以!以下是一个简单的Java代码示例,可将“Hello World”打印到控制台:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
您可以将此代码复制并粘贴到Java编辑器中,然后运行它。它将输出“Hello World”到控制台窗口。

除了写代码,它还可以帮你运行:

我的要求:

作为一个java编译器,请运行以下代码: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }

ChatGPT的回答:

好的,以下是您提供的Java代码的运行结果:

Copy

Hello World

这是因为该程序使用**System.out.println**语句将字符串“Hello World”输出到控制台。当您在命令行或控制台中运行该程序时,它将打印该字符串。

是不是很好用!接下来我们要求复杂一点的功能,我要用java调用ChatGPT的API.

第一次,高效返回了代码:

调用ChatGPT的API第一次尝试

我的要求:

Please provide a java code to call API of ChatGPT

ChatGPT:

As an AI language model, I do not have an API that can be called from a Java code. However, you can integrate the OpenAI API, which powers me, into your Java application using the following steps:

  1. Sign up for an OpenAI API key at beta.openai.com/signup/ .
  2. Install the okhttp and gson libraries in your Java project. You can do this using Maven or by manually downloading the libraries and adding them to your project's classpath.
  3. Write the Java code to make the API call to the OpenAI API. Here's an example:

import java.io.IOException;
import com.google.gson.Gson;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OpenAIAPI {
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final String API_URL = "<https://api.openai.com/v1/engines/davinci-codex/completions>";
    private static final String API_KEY = "YOUR_API_KEY";

    public static String getResponseFromGPT(String prompt) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String json = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 50, \"temperature\": 0.5}";

        RequestBody body = RequestBody.create(json, JSON);

        Request request = new Request.Builder()
                .url(API_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        String jsonString = response.body().string();

        Gson gson = new Gson();

        OpenAIResponse openAIResponse = gson.fromJson(jsonString, OpenAIResponse.class);

        return openAIResponse.getChoices()[0].getText();
    }
}

class OpenAIResponse {
    private Choice[] choices;

    public Choice[] getChoices() {
        return choices;
    }
}

class Choice {
    private String text;

    public String getText() {
        return text;
    }
}

This code defines a getResponseFromGPT method that takes a prompt as input and returns the AI-generated text response. You'll need to replace YOUR_API_KEY with your actual OpenAI API key.

Note that this code uses the OpenAI Codex API, which is one of the APIs that powers ChatGPT. Depending on your use case, you may need to use a different OpenAI API. You can find more information about the available APIs at beta.openai.com/docs/api-re….

生成代码之前,先告诉我去哪里注册,生成的代码里除了调用,还帮我解析了返回结果,最后还有解释API的作用,key去哪里找.

非常完整的代码!

第二次,给我读配置文件

我的要求: Please provide a java code sample to call API of ChatGPT, and make the parameter for calling API like "temperature" be read from property file by Spring annotation, return the java object of response.

ChatGPT的回答:

I'm sorry, but as an AI language model, I don't have the capability to directly call an API or read a property file. However, I can provide you with some guidance on how you can achieve this task in Java using Spring annotations.

To call an API in Java, you can use the RestTemplate class from the org.springframework.web.client package. Here's an example code snippet that shows how you can use RestTemplate to call an API and get the response as a Java object:

RestTemplate restTemplate = new RestTemplate();
String apiUrl = "<https://api.example.com/getTemperature?location={location}>";
String location = "New York";
TemperatureResponse response = restTemplate.getForObject(apiUrl, TemperatureResponse.class, location);

In this example, we're calling an API endpoint at https://api.example.com/getTemperature, passing in the location parameter as a query parameter. We're using the getForObject method of RestTemplate to send the GET request and get the response as a TemperatureResponse object.

To read the location parameter from a property file using Spring annotations, you can use the @Value annotation. Here's an example of how you can define a property file and read the location value using @Value:

@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {

    @Value("${temperature.location}")
    private String location;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public TemperatureResponse temperatureResponse(RestTemplate restTemplate) {
        String apiUrl = "<https://api.example.com/getTemperature?location={location}>";
        return restTemplate.getForObject(apiUrl, TemperatureResponse.class, location);
    }
}

In this example, we're defining a Spring @Configuration class AppConfig that reads the config.properties file using the @PropertySource annotation. We're using the @Value annotation to read the location property from the file and store it in a private field. Then, we're defining a RestTemplate bean and injecting it into the temperatureResponse bean method. Finally, we're using RestTemplate to call the API endpoint and get the response as a TemperatureResponse object, using the location parameter that we read from the property file.

I hope this helps! Let me know if you have any further questions.

它果然是知道怎么用注解读取配置文件的,我再加点要求.

第三次,把返回结果封装的详细些

我的要求:

Please provide a java code sample to call API of "api.openai.com/v1/completi…", and make the parameter for calling API like "temperature" be read from property file by Spring annotation, pase the response and put the value of fields like choices, created into a specific object.

ChatGPT的回答:

Sure, here's a Java code sample using the Spring framework to call the OpenAI API and read the "temperature" parameter from a properties file. The response is parsed using the Jackson JSON library and the relevant fields are extracted and placed into a custom object.

Assuming you have already added the necessary dependencies to your project, here's an example of how to use Spring's RestTemplate to make the API call:


import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
@PropertySource("classpath:application.properties")
public class OpenAIAPIClient {

  @Value("${openai.api.key}")
  private String apiKey;

  @Value("${openai.completion.temperature}")
  private float temperature;

  private final RestTemplate restTemplate = new RestTemplate();

  public CompletionResponse requestCompletion(String prompt) throws Exception {
    String url = "<https://api.openai.com/v1/completions>";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + apiKey);

    // Build the request payload
    OpenAIRequest request = new OpenAIRequest();
    request.setPrompt(prompt);
    request.setTemperature(temperature);

    HttpEntity<OpenAIRequest> entity = new HttpEntity<>(request, headers);

    ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

    ObjectMapper mapper = new ObjectMapper();
    CompletionResponse completionResponse = mapper.readValue(response.getBody(), CompletionResponse.class);

    return completionResponse;
  }
}

In this example, the apiKey and temperature values are read from a application.properties file, which should be placed in the src/main/resources directory of your project. Here's an example of what that file might look like:

openai.api.key=your_api_key_here
openai.completion.temperature=0.8

The CompletionResponse class would be a custom class that you define to hold the relevant fields from the API response. Here's an example of what that class might look like:


public class CompletionResponse {
  private String id;
  private List<CompletionChoice> choices;
  private Instant created;

  // getters and setters
}

And the CompletionChoice class might look like:


public class CompletionChoice {
  private String text;
  private float score;

  // getters and setters
}

Hope this helps!

哈哈,还告诉我要用什么类库. 这样的代码,我觉得结构清晰,注释完整,非常赏心悦目

结论

ChatGPT是一个强大的工具,可以快速轻松地生成Java代码。通过提供需求明确的文本提示,您可以获得完成特定任务的Java代码,而无需自己编写代码。这可以节省时间和精力,大大提高效率.

对此,你是如何看待?你觉得人工智能威胁到码农的职位了吗?欢迎大家评论留言.