• 给IDEA安装“AI Coding Assistant” 插件看一下ChatGPT是如何写代码的
  • 发布于 2个月前
  • 2945 热度
    0 评论
前言
最近这段ChatGPT真的非常火,和ChatGPT相关的AI 服务也是各种如火如荼的研究中。今天我们来看下ChatGPT在编码方面的应用,最近发现一个叫做“AI Coding Assistant” 的IntelliJ IDEA插件,它就是集合了ChatGPT的技术,我们来看看有多么的智能,是否以后真的有可能会代替我们程序员的工作。

插件安装
为了开始使用该插件,必须要有一个 OpenAI 的令牌。如果你不知道在哪里可以找到它,可以在https://platform.openai.com/account/api-keys这里获取,关于如何注册。百度谷歌教程一大堆。此外,下载并安装IntelliJ IDEA的AI Coding Assistant”插件:

尝试一下
生成打印hello world的代码
第一个任务先来个简单的,就是让它自动生成打印hello world的代码。

现在你给我生成一个Person类。

现在给我创建一个函数来返回生成的人员列表

有了person数据以后,我们可以实现一些简单的算法,比如找到列表中最年长的人,列表中人的最小/最大/平均年龄

其中有趣的部分是我们可以要求更新现有代码。因为我知道使用 Java Stream API 编写相同算法的更好方法,所以让我们尝试让它进行重构

我们可以创建一个函数并要求它根据函数名的意思生成代码。

然后你在给我把javadoc也补充了把

那你还能给我的代码添加注释吗,解释下这段代码是干嘛的吗?

最后我们来看看通过这个AI插件生成的最终的代码长啥样?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.NoSuchElementException;
 //堆代码 duidaima.com
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
        final List<Person> people = generatePeople();
        // find oldest person in the list
        Person oldestPerson = people.stream()
            .max(Comparator.comparing(Person::getAge))
            .orElseThrow(NoSuchElementException::new);
        System.out.println("Oldest person is: " + oldestPerson.getName());
        // find max,min,avg age of the people
        IntSummaryStatistics stats = people.stream()
            .mapToInt(Person::getAge)
            .summaryStatistics();
        System.out.println("Max Age: " + stats.getMax());
        System.out.println("Min Age: " + stats.getMin());
        System.out.println("Avg Age: " + stats.getAverage());
    }

    public static List<Person> generatePeople() {
        return Arrays.asList(
            new Person("John", 25),
            new Person("Jane", 30),
            new Person("Jack", 20),
            new Person("Jill", 35)
        );
    }

    /**
* Capitalizes the first letter of a given string and lowercases the rest.
*
* @param s The string to capitalize
* @return The capitalized string
*/
    public static String capitalize(String s) {
        /*
This code checks if the length of the string "s" is 0. If it is, it returns the string.
If not, it returns the first character of the string in uppercase and the rest of the characters in lowercase.
*/
        if (s.length() == 0)
            return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }
}

// class Person with name and age
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

结论
利用ChatGPT这样的AI可以生成一些代码,如上面的例子所示,但是面对一些复杂的业务还是做不到的。我们可以借助这样的工具,帮助我们提高工作上的效率,但是也不用担心他们会取代我们。
用户评论