Reputation: 11
I want to get an Array with the reversed number when I invoke the method (Given a random non-negative number, you have to return the digits of this number within an array in reverse order.) I initalised a scanner, but whenever I execute, I only get the address in the heap I suppose (for example: [I@66a29884). I know this problem also occurs when we have String, which why we have the toString-Method. Is there a way I can print the array or the reversed numbers out in the console?
public class ConvertNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Long n = Long.parseLong(scanner.nextLine());
digitize(n);
}
public static int[] digitize(long n) {
int[] digitized = new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray() ;
System.out.println(digitized);
return digitized;
}
}
Upvotes: 1
Views: 395
Reputation: 2396
You have to change Long
to String
because [I@66a29884)
is String. using java stream you can reverse string easily.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.*;
public class Main
{
public static String digitize(String n) {
return Stream.of(n)
.map(str->new StringBuilder(str).reverse())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = scanner.next();
System.out.print(digitize(n));
}
}
Upvotes: 3