Why do reverseString() and for() return error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why do reverseString() and for() return error?

I cannot find any syntax error. Yet the code does not work. https://code.sololearn.com/caB7uzPOB5Xv/?ref=app

27th Nov 2021, 6:08 PM
Billy Beagle
4 Answers
+ 4
// I fixed a few lines of code import java.util.Scanner; class ReverseFunction { static String reverseString(String w) { String r=""; char[] arr = w.toCharArray(); for(int i=arr.length-1; i>=0; i--) r += arr[i]; return r; } } public class ReverseCode { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word = sc.nextLine(); System.out.println(ReverseFunction.reverseString(word)); } }
27th Nov 2021, 6:19 PM
SoloProg
SoloProg - avatar
+ 3
Billy Beagle Every method needs a return type. If you don't want to return a value return type is void: public static void yourMethod() In your case you want to return a String: public static String yourMethod() Btw: Your method would return the last char of your String. Your loop is okay, you only need to add each char to a new empty String. After the loop return this String. (See SoloProg solution)
27th Nov 2021, 6:35 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
//correction are in comments... import java.util.Scanner; class ReverseFunction { static reverseString(String string) { //return type missing , add it //public static void reverseString(String string){ char[] arr = string.toCharArray(); for(int i=arr.length-1;; i>=0; i++) { //uee i-- instead of i++ return arr[i]; // print value instead of returning.., use System.out.print(arr[I]); return returns to calling at first iteration. Not returns all. not prints all. you may misunderstood ' return' } } } public class ReverseCode { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word = sc.nextLine(); System.out.println(reverseString(word));//method is in another class so call it by class name. like // ReverseFunction.reverseString(word); } }
27th Nov 2021, 6:30 PM
Jayakrishna 🇮🇳
+ 2
SoloProg Denise Roßberg Jayakrishna🇮🇳 thank you all, it works now! A nice day to all! :)
28th Nov 2021, 10:42 AM
Billy Beagle