How to make ChatGPT act as a meticulous Java code optimizer?
Note: This article uses New Bing (GPT4.0) to demonstrate
1. Let him play a Java software developer
Step one: Let ChatGPT play the role of a Java software developer
- Prompt word plug-in: Address: ChatGPT BingChat GPT3 Prompt Generator App (Streamlit) - a Hugging Face Space by Kaludi
Java Software Developer Java Software Developer
I want you to act as a Java software developer. I will provide you with a list of commands and you will implement them. My first request is "I need help creating a Java application."
2. Prepare a Very good Java code example
Step 2: We prepare a poorly written Java code example
- Bad Java Example:
public int calculateUsingIfElse(int a, int b, String operator) { int result = 0; if (operator.equals("add")) { result = a + b; } else if (operator.equals("subtract")) { result = a - b; } else if (operator.equals("multiply")) { result = a * b; } else if (operator.equals("divide")) { if (b == 0) { throw new IllegalArgumentException("Cannot divide by zero"); } result = a / b; } else if (operator.equals("modulus")) { if (b == 0) { throw new IllegalArgumentException("Cannot divide by zero"); } result = a % b; } else if (operator.equals("power")) { result = (int) Math.pow(a, b); } else if (operator.equals("square root")) { if (a < 0) { throw new IllegalArgumentException("Cannot take square root of negative number"); } result = (int) Math.sqrt(a); } else if (operator.equals("absolute value")) { result = Math.abs(a); } else if (operator.equals("negate")) { result = -a; } else { throw new IllegalArgumentException("Invalid operator"); } return result; }
3. Let him optimize this code
Step 3: Let newBing (ChatGPT) optimize this code
- And requires "organizing it into a more elegant code structure, such as automatically splitting sub-functions, reducing if and loop nesting, and even implementing some design patterns."
// 定义一个接口,表示不同的运算策略 public interface OperationStrategy { int apply(int a, int b); } // 定义一个枚举,表示不同的运算符和对应的策略 public enum Operator { ADD((a, b) -> a + b), SUBTRACT((a, b) -> a - b), MULTIPLY((a, b) -> a * b), DIVIDE((a, b) -> { if (b == 0) { throw new ArithmeticException("Cannot divide by zero"); } return a / b; }), MODULUS((a, b) -> { if (b == 0) { throw new ArithmeticException("Cannot divide by zero"); } return a % b; }), POWER((a, b) -> (int) Math.pow(a, b)), SQUARE_ROOT((a, b) -> { if (a < 0) { throw new ArithmeticException("Cannot take square root of negative number"); } return (int) Math.sqrt(a); }), ABSOLUTE_VALUE(Math::abs), NEGATE(a -> -a); private final OperationStrategy strategy; Operator(OperationStrategy strategy) { this.strategy = strategy; } public int apply(int a, int b) { return strategy.apply(a, b); } } // 定义一个方法,根据运算符和操作数来计算结果 public int calculateUsingStrategy(int a, int b, String operatorName) { // 根据运算符名称找到对应的枚举常量,如果没有找到则抛出异常 Operator operator = Operator.valueOf(operatorName.toUpperCase()); if (operator == null) { throw new IllegalArgumentException("Invalid operator"); } // 调用枚举常量的apply方法来执行相应的策略 return operator.apply(a,b); }
4. Let him write a single test
The fourth step: We finally ask him to finish - write a single test Test it
import org.junit.Test; import static org.junit.Assert.*; // 定义一个测试类,用@Test注解标记要执行的测试方法 public class CalculatorTest { // 定义一个测试方法,用assertEquals方法来验证计算结果是否正确 @Test public void testAdd() { int result = calculateUsingStrategy(3, 5, "add"); assertEquals(8, result); } // 定义其他的测试方法,分别测试不同的运算符和操作数 @Test public void testSubtract() { int result = calculateUsingStrategy(10, 4, "subtract"); assertEquals(6, result); } @Test public void testMultiply() { int result = calculateUsingStrategy(7, 9, "multiply"); assertEquals(63, result); } @Test public void testDivide() { int result = calculateUsingStrategy(12, 3, "divide"); assertEquals(4, result); } // 定义一个测试方法,用assertThrows方法来验证抛出了预期的异常 @Test public void testDivideByZero() { assertThrows(ArithmeticException.class, () -> calculateUsingStrategy(10,0,"divide")); } // 定义其他的测试方法,分别测试不同的异常情况 @Test public void testModulusByZero() { assertThrows(ArithmeticException.class, () -> calculateUsingStrategy(10,0,"modulus")); } @Test public void testSquareRootOfNegativeNumber() { assertThrows(ArithmeticException.class, () -> calculateUsingStrategy(-4,-2,"square root")); } // 定义一个测试方法,用assertThrows方法来验证抛出了预期的异常 @Test public void testInvalidOperator() { assertThrows(IllegalArgumentException.class, () -> calculateUsingStrategy(10,-2,"foo")); } }
Finally, data security is the biggest issue. Do not post data to ChatGPT indiscriminately, especially when it involves back-end core storage account passwords, company core business data, and departments. Core strategic planning, etc. Because first of all, ChatGPT will use your question and answer corpus for training; secondly, you can't predict what prompt word the LLM model will answer with the information you inadvertently leaked.
Despite its flaws, the LLM model represented by ChatGPT can greatly improve our development efficiency when acting as our omniscient teacher and tireless universal Util code writer, especially In the fields of data analysis, front-end, unit testing, reconstruction and other fields.
Just like what was written in the first step of the article, ChatGPT is like a versatile identity. You can let him play any role, and Every role can be played in this role range to help us achieve a better life.
More interesting usages are waiting for everyone to discover.
The above is the detailed content of How to make ChatGPT act as a meticulous Java code optimizer?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DALL-E 3 was officially introduced in September of 2023 as a vastly improved model than its predecessor. It is considered one of the best AI image generators to date, capable of creating images with intricate detail. However, at launch, it was exclus

Translator | Bugatti Review | Chonglou This article describes how to use the GroqLPU inference engine to generate ultra-fast responses in JanAI and VSCode. Everyone is working on building better large language models (LLMs), such as Groq focusing on the infrastructure side of AI. Rapid response from these large models is key to ensuring that these large models respond more quickly. This tutorial will introduce the GroqLPU parsing engine and how to access it locally on your laptop using the API and JanAI. This article will also integrate it into VSCode to help us generate code, refactor code, enter documentation and generate test units. This article will create our own artificial intelligence programming assistant for free. Introduction to GroqLPU inference engine Groq

Imagine an artificial intelligence model that not only has the ability to surpass traditional computing, but also achieves more efficient performance at a lower cost. This is not science fiction, DeepSeek-V2[1], the world’s most powerful open source MoE model is here. DeepSeek-V2 is a powerful mixture of experts (MoE) language model with the characteristics of economical training and efficient inference. It consists of 236B parameters, 21B of which are used to activate each marker. Compared with DeepSeek67B, DeepSeek-V2 has stronger performance, while saving 42.5% of training costs, reducing KV cache by 93.3%, and increasing the maximum generation throughput to 5.76 times. DeepSeek is a company exploring general artificial intelligence

Plaud, the company behind the Plaud Note AI Voice Recorder (available on Amazon for $159), has announced a new product. Dubbed the NotePin, the device is described as an AI memory capsule, and like the Humane AI Pin, this is wearable. The NotePin is

Earlier this month, researchers from MIT and other institutions proposed a very promising alternative to MLP - KAN. KAN outperforms MLP in terms of accuracy and interpretability. And it can outperform MLP running with a larger number of parameters with a very small number of parameters. For example, the authors stated that they used KAN to reproduce DeepMind's results with a smaller network and a higher degree of automation. Specifically, DeepMind's MLP has about 300,000 parameters, while KAN only has about 200 parameters. KAN has a strong mathematical foundation like MLP. MLP is based on the universal approximation theorem, while KAN is based on the Kolmogorov-Arnold representation theorem. As shown in the figure below, KAN has

To learn more about AIGC, please visit: 51CTOAI.x Community https://www.51cto.com/aigc/Translator|Jingyan Reviewer|Chonglou is different from the traditional question bank that can be seen everywhere on the Internet. These questions It requires thinking outside the box. Large Language Models (LLMs) are increasingly important in the fields of data science, generative artificial intelligence (GenAI), and artificial intelligence. These complex algorithms enhance human skills and drive efficiency and innovation in many industries, becoming the key for companies to remain competitive. LLM has a wide range of applications. It can be used in fields such as natural language processing, text generation, speech recognition and recommendation systems. By learning from large amounts of data, LLM is able to generate text

Graph Retrieval Enhanced Generation (GraphRAG) is gradually becoming popular and has become a powerful complement to traditional vector search methods. This method takes advantage of the structural characteristics of graph databases to organize data in the form of nodes and relationships, thereby enhancing the depth and contextual relevance of retrieved information. Graphs have natural advantages in representing and storing diverse and interrelated information, and can easily capture complex relationships and properties between different data types. Vector databases are unable to handle this type of structured information, and they focus more on processing unstructured data represented by high-dimensional vectors. In RAG applications, combining structured graph data and unstructured text vector search allows us to enjoy the advantages of both at the same time, which is what this article will discuss. structure

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo
