Vishal Vishal - 2 months ago 6
Java Question

Error regarding StringBuffer

So I'm trying to write a program in which it takes a user input as an integer and outputs the reverse of that. I created a method to reverse the integer but I get an error that says I have to convert the method type to

StringBuffer
instead of an
int
. But when I use the same code in the main method I don't get such an error. This is the method that i wrote:

public class TestProgram {
public static int reverse(int number){

StringBuffer str = new StringBuffer();

str.append(number);

str.reverse();

return str;
}


And this is the code that i wrote in the main method which works:

import java.util.Scanner;
public class test{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter value: ");
int num = input.nextInt();

StringBuffer str = new StringBuffer();

str.append(num);

str.reverse();
System.out.println(str);

}
}

Answer

You have method that declared to return int but try to return StringBuffer.

You have two options. Declare method to return StringBuffer or parse string to int with Integer.parseInt(sb.toString) before returning it.