【问题标题】:Multiplication of two 64 digit number_Gettin Input Mismatch Exception两个 64 位数字相乘_Gettin Input Mismatch Exception
【发布时间】:2020-07-26 12:28:30
【问题描述】:
public class Karatsubamultiplication {

    public static void multiply(long ac , long ad, long bc, long bd, long digits)
    
    {
      double mul=0;
      
      mul = Math.pow(10, digits) *ac + Math.pow(10, digits/2)*(ad+bc)+bd;
      
      System.out.println("The multiplication answer is "+mul);
    }
    
    public static long[] splitnum(long n1) {
        long[] split= new long[3];
        long divider=1;
        long num =0;
        long counter=0;
        num=n1;
        while(num>0) {
            num=num/10;
            counter=counter+1;
        }
        split[2]=counter;
        for(long i=0;i<counter/2;i++) {
            divider*=10;
        }       
        split[0]=n1/divider;
        split[1]=n1%divider;
                
        return split;       
    }
    
    public static void main(String[] args) {
            
        Scanner sc = new Scanner(System.in);    
        System.out.println("Enter value of n1 and n2 ");
        long n1 = sc.nextLong();
        long n2 = sc.nextLong();
        long ac=0,ad=0,bc=0,bd=0,digits=0;
        if(n1/10==0 && n2/10==0)
        {
            System.out.println("The multiplication answer is "+n1*n2);
        }
        else
        {
            long[] a= splitnum(n1);
            long[] c =splitnum(n2);     
            ac = a[0]*c[0];
            ad = a[0]*c[1];
            bc= a[1]*c[0];
            bd= a[1]*c[1];
            digits=a[2];
            multiply(ac,ad,bc,bd,digits);
            
        }
                                
    }       
}

两个64位数字相乘_Gettin输入不匹配异常

查询:当我给出 2 个 64 位数字时,结果将是 128 位。获取输入不匹配异常:(

需要帮助来增强此代码以处理此异常。>

【问题讨论】:

    标签: java algorithm exception multiplication inputmismatchexception


    【解决方案1】:

    InputMismatchExceptionnextLong()方法抛出,当用户输入的输入实际上不是长时。

    您使用扫描仪的方式意味着nextLong 正在寻找一个空格、输入(换行符)、流的结尾或其他空格,然后会将其前面的所有字符解析为长字符。请注意,这意味着输入必须包含可选的 +-,然后是一堆数字,仅此而已,并且数字必须介于 -2^63 和 +2^63-1 之间(所以,在-9223372036854775808+9223372036854775807 之间)。任何低于/高于的数字都不长,因此会导致该异常。

    Fix:好吧,你告诉我。你想让这个程序做什么?任何超出该范围的数字首先不适合长数据类型

    如果您不需要您的程序来处理极端数字,那么.. 不要输入它们。

    如果这样做,则需要完全替换此代码;根本不要调用 .nextLong() 。据推测,只需调用 .next() 并使用 java.math.BigInteger 而不是 longs,它可以接受任何大小的数字。

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多