sam
sam

Reputation: 1

Problems with the size of inputs, java noob

import java.lang.StringBuffer;
import java.util.Scanner;
public class test {

   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer();
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter number to be reversed: ");
      int x = scan.nextInt();
      Integer number = new Integer(x);
      String reverse = new String();

      for(int i = 0; i <= number.toString().length()-1; i++) {
         reverse = new StringBuffer(reverse).insert(i, number.toString().charAt(number.toString().length()-(1+i))).toString();
      }

      System.out.println(reverse);
   }
}

I have this code, the problem is that any imput over 9 digits will raise an error:

Exception in thread "main" java.util.InputMismatchException: For input string: "4444444444"
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.main(test.java:9)

Does anyone know why this is the case?

Upvotes: 0

Views: 1072

Answers (3)

Speck
Speck

Reputation: 2309

Instead of int and Integer use long and Long. int only goes up to 2,147,483,647

update: Looking at your code again, Why are you puling in ints when you're using it as a String.

Use char for each character, print an error if they enter a non-numeric. This way they can enter as long a number as they please.

Upvotes: 4

iluxa
iluxa

Reputation: 6969

Even if you use Long, you'll still be able to type a number that's just too long. Do this:

int x;
boolean isNumberGood = false;
try { 
  x = Scanner.nextInt();
  isNumberGood = true;
} catch (java.util.InputMismatchException ex) {
  System.out.println("bad number!");
}

and don't proceed if isNumberGood isn't true

Upvotes: 2

New Guy
New Guy

Reputation: 9126

An int can hold numbers within the following range:

-2,147,483,648 to +2,147,483,647

User long instead of int and use scan.nextLong(); to get the input.

Upvotes: 3

Related Questions