整数Java太长了

时间:2013-05-09 12:57:56

标签: java

  public static void gramstoAtoms()
  {
   System.out.println("Enter Amount of grams");
   Scanner keyboard = new Scanner(System.in);
   long x = keyboard.nextLong();
   System.out.println("Enter Unit Grams");
   long y = keyboard.nextLong();
   long result = x/y;
   long answer = result*60200000000000000000000;
   System.out.println(answer + "Atoms");
  }

如何更改此代码,以便我没有得到一个整数太长的错误?

4 个答案:

答案 0 :(得分:7)

只使用BigInteger而不是long

BigInteger bi=new BigInteger("6020000000000000000000");

您的方法:

public static void gramstoAtoms()
  {
   System.out.println("Enter Amount of grams");
   Scanner keyboard = new Scanner(System.in);
   String x = keyboard.nextLine();
   System.out.println("Enter Unit Grams");
   String y = keyboard.nextLine();
   BigInteger result = new BigInteger(x).divide(new BigInteger(y));
   BigInteger answer = result.multiply(new BigInteger("60200000000000000000000"));
   System.out.println(answer + "Atoms");
  }

如果您的xy很小,您可以使用简单的long,但是当乘以602 ....... 0000时使用BigInteger < / p>

答案 1 :(得分:3)

如果我没记错的话,Avogadro的号码是6.02e24long的最大值为9,223,372,036,854,775,807,但不够大。您需要BigInteger

答案 2 :(得分:1)

这是一个没有BigInteger的解决方案:

long answer = result * 602;
System.out.println(answer + "00000000000000000000Atoms");

答案 3 :(得分:0)

Dima Goltsman是正确的,您必须使用BigInteger修复它