I am very new to Java and I have no other programming experience. I am struggling with a homework question and I have only gotten so far. I am very sure this question is very s
There are two ways to do this. I won't give you the code, but hopefully I'll put you in the correct direction.
You can turn the integer into a string and reverse the string. Then turn it back into an integer. If you want to do this, I suggest looking at Integer.parseInt and String.valueOf.
This is probably the better way. Integers in programming languages will return only the quotient of the answer. So when you do 5 / 2, it returns 2. The modulo returns the remainder of the division. So 5 % 2 (% is the modulo operator) would be equal to 1.
Observe that you can use the division and modulo of 10 to reverse the integer.
And as mentioned in one of the comments, you'll want to only return the result from your function. Remove the System.out.println from the reverse function and put it in main. So you would call it like this:
public static void main(String[] args) {
System.out.println(reverse(123));
}
EDIT: This is in response to the comments.
In Java, there are two types of data. Native types and objects. The native types are int, double, float, long, byte, and char. These are the only types that are not objects and toString doesn't exist for them. Each one of them has an Object that you can use instead though. For example, int's object counterpart is Integer.
Everything else is an object and is derived from the base class Object and is related to object-oriented programming. The toString method is used to give a human-readable string representation of whatever object it is called on.
Any class can have their own implementation of the toString method which will return (ideally) a human-readable string.
x = Integer.parseInt(x.toString().Reverse());
Reverse of 123 is 321 Observe that 123 = 100*1 + 10*2 + 1*3 and 321 = 1*1 + 10*2 + 100*3
How do you split 123 in 1,2,3? How do you iterate through all the digits?
Are you familiar with loop constructs?
Do you know what division remainder is?
You can try something like below.
public class BlackBelt8 {
public static void main(String[] args) {
System.out.println(reverse(5433));
}
public static int reverse(int x){
String aString = String.valueOf(x);
StringBuilder strBuild = new StringBuilder(aString);
StringBuilder strReverseBuild = strBuild.reverse();
int resultInt = Integer.parseInt(strReverseBuild.toString());
return resultInt;
}
}