gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
write a method in java which loops through a string and then displays its contents
- User
write a method in java which loops through a string and then displays its contents
- Assistant
Sure! Here's a Java method called
displayStringContent, which loops through a string and displays its contents:javapublic class Main { public static void main(String[] args) { String str = "Hello, World!"; displayStringContent(str); } public static void displayStringContent(String str) { for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); System.out.println(ch); } } }In this method, we pass a string
stras a parameter. The method uses aforloop to iterate through each character in the string. For each iteration, it retrieves the character at the current index using thecharAtmethod and prints it usingSystem.out.println().