Sahar Max - 3 months ago 9

Java Question

Example: when you type "1234567", it`s display "0 1 2 3 4 5 6 7". How can I rid of "0" in front part?

`public static void main(String[] args){`

int num = 0;

int eachNum = 0;

Scanner input = new Scanner(System.in);

System.out.print("Enter your number here: ");

num = input.nextInt();

int num2 = num;

int length = String.valueOf(num).length();

while ( length >= 0 ) {

int substraction =(int) Math.pow(10, length);

int sub = (int) substraction;

eachNum = num2 / sub % 10;

System.out.print(eachNum + "\t");

length--;

}

}//end main method

Answer

Consider the first iteration.

`length`

is `7`

.

`pow(10, 7)`

is `10,000,000`

(I've put commas in for clarity).

`num2 / sub % 10;`

is evaluated as `(num2 / sub) % 10`

due to the *precedence* of `/`

and `%`

being the same so evaluation is from left to right.

This is `(1,234,567 / 10,000,000) % 10`

which is `0 % 10`

since *integer division* truncates the number. So your first output is `0`

.

The simplest fix is probably to subtract 1 from the initial value of `length`

.