gudii9
asked on
reverse digits of a number using for loop
Hi,
above code generate below output
123
null321
i do not want null before output insted i want like beloe
123
321
how to fix it and improve it. please advise
package ForLoop;
import java.util.Scanner;
public class ReverseDigits {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
ReverseDigits rd = new ReverseDigits();
rd.reverseDigits(num);
}
private void reverseDigits(int num)
{
// TODO Auto-generated method stub
String reverse =
null;
for(;num>0;num=num/10){
reverse=reverse+num%10;
}
System.out.println(reverse);
}
}
above code generate below output
123
null321
i do not want null before output insted i want like beloe
123
321
how to fix it and improve it. please advise
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
int rem, rev=0; // why compiler happy about not initializing rem where as screaming if i do not initialize rev with 0????
package for_loops;
import java.util.Scanner;
public class reverse_digits {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter a number...");
int x = sc.nextInt();
int rem, rev=0; // why compiler happy about not initializing rem where as screaming if i do not initialize rev with 0????
for (;x > 0; x = x / 10)
{
rem = x % 10;
rev = rev * 10 + rem;
}
System.out.println("Reversed number is "+rev);
}
}
can you please advise on this
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Open in new window
3253//gives wrong output instead i like to see 523
how above code different from below
Open in new window