patternjavaMinor
Printing every digit of a number
Viewed 0 times
numberdigitprintingevery
Problem
Which of these three methods is better?
How can I rewrite the
import java.util.* ;
public class anycode{
public static void print_digits3(int num){
//this method converts integer to string and parses it
int digit = 0 ;
String num_str = new Integer(num).toString() ;
int counter = 0 ;
while(counter != num_str.length()){
System.out.println("digit: " + num_str.charAt(counter) + "| real integer digit: " + Integer.parseInt(num_str.substring(counter,counter+1))) ;
counter++ ;
}
}
public static void print_digits4(int num){
//this method converts integer to array of chars and parses it
char[]num_sequence_of_chars = new Integer(num).toString().toCharArray() ;
for(int i = 0 ; i = 0){
temp = num ;
base = Math.pow(10,num_len) ;
num = num / (int)base ;// type recasting to int is a must, it does not work without it - no idea why
System.out.println("num :" + num) ;
num = (int) temp % (int)base ;
num_len-- ;
}
}
public static void print_digits(int num){
int digit = 0 ;
while(num != 0 ){
digit = num%10 ;
System.out.print(digit + "\t") ;
num = num/ 10 ;
}
}
public static void main(String args[]){
print_digits2(7658) ;
System.out.println("--------------------------") ;
print_digits3(7658) ;
}
}How can I rewrite the
print_digits2? I want a more efficient MATH method of doing - no converting to string \ char[].Solution
To be frank, I don't really know why you need such methods to print out individual characters, I'll just make my suggestions based on what you have...
Not sure what's your aversion to using the
- Your class name
anycodeshould be inPascalCase.
- Your method names should be in
camelCase.
- Eclipse tells me that the assignments
int digit = 0;inprint_digits3andprint_digits2are not used.
- You have this comment:
// type recasting to int is a must, it does not work without it - no idea why- that's because when you divide anintwith adouble, the result will bedoubletype but you are assigning that to anintvalue. Therefore, you are required to cast thedoubleinto anintfirst for the assignment to be correct.
- Recommended to use
Integer.valueOf()instead ofnew Integer().
Not sure what's your aversion to using the
char[] way of doing the same task, but here's a suggested approach anyways for comparison (to your print_digits4 method):private static void printDigits( int num ) {
for ( char c : String.valueOf( num ).toCharArray() ) {
System.out.println( c );
}
}Code Snippets
private static void printDigits( int num ) {
for ( char c : String.valueOf( num ).toCharArray() ) {
System.out.println( c );
}
}Context
StackExchange Code Review Q#51349, answer score: 6
Revisions (0)
No revisions yet.