简体   繁体   中英

Extracting a number in Java isn't working as expected

This program is supposed to print the numbers (indiviual digits) in a number `

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number");
    int number = sc.nextInt();
    int Size = 0;
    String Conversion = Integer.toString(number);
    Size = Conversion.length();
    int n = 0;
    while (n <= Size){
      int d = number%10;
      int power = Size - 2;
      number = (number/(10^(power)));
      System.out.println(d);
      n += 1;
    }
  }
}

`

Really Appreciate for Anyone for Took time to help me. Thanks

For some reason I get 1 9 3.

instead of 1 3 4

using the debugger gives me some hint, Specifically this block `

number = (number/(10^(power)));

`

for second iteration the value is +4 than expected, 3.

for third Its okay. changing and adding +4 on that block gives 1 3 7 4

Found it,! Credit OH GOD SPIDERS, tkausl

Solution 1: Instead of using carrot characters in

number = (number/(10^(power)));

use Math.pow function.

Solution 2:

Don't use (number/(10^(power)) instead just divide by 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM