1
  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");
  }

How do I change this code so that I don't get an integer is too long error?

4 Answers4

7

just use BigInteger instead of long

BigInteger bi=new BigInteger("6020000000000000000000");

for your method:

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");
  }

and if your x and y are small, you can use them with simple long, but when multiply by the 602.......0000 use the BigInteger

Dima
  • 8,586
  • 4
  • 28
  • 57
3

If I recall correctly, Avogadro's number is 6.02e24. A long has a max value of 9,223,372,036,854,775,807, which isn't big enough. You'll need BigInteger.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

It's a solution without BigInteger:

long answer = result * 602;
System.out.println(answer + "00000000000000000000Atoms");
johnchen902
  • 9,531
  • 1
  • 27
  • 69
0

Dima Goltsman is correct, you had to fix it using the BigInteger

Splash City
  • 11
  • 1
  • 3