Write Java code to implement a personal AI for one person
- User
Write Java code to implement a personal AI for one person
- Assistant
Write Java code to implement a personal AI for one person
Here's an example of Java code that implements a personal AI for one person:
import java.util.Scanner;
public class PersonalAI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PersonalAI personalAI = new PersonalAI();
System.out.println("Hello! How can I assist you today?");
while (true) {
String userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("bye")) {
System.out.println("Goodbye! Have a great day!");
break;
}
String response = personalAI.generateResponse(userInput);
System.out.println(response);
}
scanner.close();
}
public String generateResponse(String userInput) {
if (userInput.contains("hello") || userInput.contains("hi")) {
return "Hello! How can I help you today?";
} else if (userInput.contains("how are you")) {
return "I'm an AI, so I don't have feelings. But thanks for asking!";
} else if (userInput.contains("time")) {
return "The current time is " + getCurrentTime();
} else if (userInput.contains("weather")) {
return "Sorry, I am not programmed to check the weather. Please try a weather app.";
} else {
return "I'm sorry, I don't understand. Can you please rephrase or provide more information?";
}
}
public String getCurrentTime() {
// Implement your logic to get the current time
// You can use java.time or java.util.Calendar for this purpose
// Here's an example using java.time.LocalDateTime:
// return LocalDateTime.now().toString();
return "12:00 PM"; // Placeholder example
}
}
In this code, we create a PersonalAI class that provides a basic conversational interface with the user. The AI responds to user inputs with predefined responses based on the content of the input.
The generateResponse method takes the user's input as a parameter and generates a response accordingly. It checks for specific keywords like "hello", "hi", "how are you", and "time" to determine the appropriate response to provide.
The main method drives the overall conversation. It repeatedly prompts the user for input until the user enters "bye" to end the conversation. The user input is then passed to the generateResponse method to generate the AI's response, which is printed to the console.
Note: This implementation is a bare minimum and you can extend it further based on your requirements to make it more intelligent and functional.