Reputation: 87
I'm trying to convert an integer into an array of digits, then print those digits out in order. It's an early problem in Java: How to Program, and I'm confused as to why I can't make it work.
Here's my class:
public class AnyDigits {
private int[] ns;
public AnyDigits(int n){
this.ns = new int[String.valueOf(n).length()];
for(int i = 0, x = n; x > 0; i++, x = x / 10){
this.ns[i] = x % 10;
}
}
public void printDigits(){
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
}
}
I have this code in my main method:
AnyDigits digitsTest = new AnyDigits(42339);
digitsTest.printDigits();
Any comments on the organisation, style and formatting of my code are also welcomed.
Any help gratefully received!
Upvotes: 0
Views: 81
Reputation: 18712
Another way aside from BackSlash's answer-
private static int[] makeArrayFromInt(final int val){
String temp = String.valueOf(val);
int[] digits = new int[temp.length()];
for(int i = 0; i < temp.length(); i++){
digits[i] = Integer.parseInt(temp.substring(i, i + 1));
}
return digits;
}
Test:
int[] digits = makeArrayFromInt(12234);
for(int i = 0; i < digits.length; i++){
System.out.println(digits[i]);
}
Upvotes: 2
Reputation: 22243
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
This won't work, you are iterating while i==0
, i
will never be 0
at the first loop unless this.ns.length == 1
.
You need
for(int i = this.ns.length - 1; i != 0; i--){
System.out.printf("%d ", this.ns[i]);
}
or
for(int i = this.ns.length - 1; i >= 0; i--){
System.out.printf("%d ", this.ns[i]);
}
Anyway, if you want to print an array, you can just do
System.out.println(Arrays.toString(yourArray));
Upvotes: 4