利用ChatGPT這樣的AI可以生成一些代碼,如上面的例子所示,但是面對一些復雜的業(yè)務還是做不到的。我們可以借助這樣的工具,幫助我們提高工作上的效率,但是也不用擔心他們會取代我們。
?前言
最近這段ChatGPT?真的非常火,和ChatGPT?相關的AI 服務也是各種如火如荼的研究中。今天我們來看下ChatGPT?在編碼方面的應用,最近發(fā)現一個叫做“AI Coding Assistant?” 的IntelliJ IDEA?插件,它就是集合了ChatGPT的技術,我們來看看有多么的智能,是否以后真的有可能會代替我們程序員的工作。
插件安裝
為了開始使用該插件,必須要有一個 OpenAI? 的令牌。如果你不知道在哪里可以找到它,可以在https://platform.openai.com/account/api-keys這里獲取,關于如何注冊。百度谷歌教程一大堆。
此外,下載并安裝IntelliJ IDEA的AI Coding Assistant”插件:

圖一——IntelliJ IDEA 設置中的 “AI Coding Assistant”插件
嘗試一下
- 生成打印hello world的代碼?
第一個任務先來個簡單的,就是讓它自動生成打印hello world的代碼。

- 生成一個pojo
現在你給我生成一個Person類。

- 現在給我創(chuàng)建一個函數來返回生成的人員列表?

- 有了person數據以后,我們可以實現一些簡單的算法,比如找到列表中最年長的人,列表中人的最小/最大/平均年齡?

- 其中有趣的部分是我們可以要求更新現有代碼。因為我知道使用 Java Stream API 編寫相同算法的更好方法,所以讓我們嘗試讓它進行重構

- 我們可以創(chuàng)建一個函數并要求它根據函數名的意思生成代碼。?

- 然后你在給我把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;
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可以生成一些代碼,如上面的例子所示,但是面對一些復雜的業(yè)務還是做不到的。我們可以借助這樣的工具,幫助我們提高工作上的效率,但是也不用擔心他們會取代我們。