为什么这个程序不允许我划分

时间:2014-08-21 17:47:06

标签: java

我注意到我找不到真正大数字的数字。我决定使用biginteger来解决这个问题,但不会让我分开它们。我也将其中一个分区变成了大型分区方法,但它仍然给了我一个红旗。任何人都可以帮我弄清楚为什么会这样吗?除法也不起作用。我将一个分区改为分区方法,剩下的分区为常规分区。

//This class test the recursive method to see how many digits are in a number
public class TestDigits {

public static void main(String[] args) {// main method to test the nmbDigits method
    Scanner c = new Scanner(System.in);
    try{
    System.out.println("Input an integer number:");
     BigInteger number = c.nextBigInteger() ;
    System.out.println(nmbDigits(number));}
    catch (InputMismatchException ex){
    System.out.println("incorrect input, integer values only.");
System.exit(1);}}


static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
    int digits = 0;
    if (c.divide(10) == 0){
        digits++;}
      else if (c / 10 != 0){
        digits++;
        BigInteger count = c/10;
        do {
            count = count/10;
            digits++;}
          while (count != 0);}
    return digits;}
}

2 个答案:

答案 0 :(得分:6)

您不能在/的实例上使用除法运算符BigInteger。此运算符仅适用于原始数字类型。这就是BigInteger类具有divide方法的原因。

BigInteger result = c.divide(new BigInteger("10"));可行。

答案 1 :(得分:0)

public class TestDigits {

public static void main(String[] args) {// main method to test the nmbDigits method
    Scanner c = new Scanner(System.in);
    try{
    System.out.println("Input an integer number:");
     BigInteger number = c.nextBigInteger() ;
    System.out.println(nmbDigits(number));}
    catch (InputMismatchException ex){
    System.out.println("incorrect input, integer values only.");
System.exit(1);}}


static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
    long digits = 0;
    if (c.divide(BigInteger.valueOf(10L)) == BigInteger.valueOf(0L)){
        digits++;}
      else if (c.divide(BigInteger.valueOf(10L)) != BigInteger.valueOf(0L)){
        digits++;
        long count = (c.divide(BigInteger.valueOf(10L))).longValue();
        do {
            count = count/10;
            digits++;}
          while (count != 0);}
    return BigInteger.valueOf(digits);}
}