0

It only appears when I enter 10 or more numbers that are 3's and 7's. It is coming from this method below, I tested it without this method. Here is the code

Scanner input = new Scanner(System.in);
    System.out.print("Enter a positive integer...");
    int num = input.nextInt();

    // Outputs
    System.out.println("Number of digits in number is " + numberDigits(num));
    System.out.println("Number begins with " + firstNum(num));
    System.out.println("Number ends with " + lastNum(num));
    System.out.println("Does number begin with 7? " + beginWith(num, 7));
    System.out.println("Does number begin with 3? " + beginWith(num, 3));
    System.out.println("Does number contain a 7? " + contains(num, 7));
    System.out.println("Does number contain a 3? " + contains(num, 3));
    System.out.println("Is the number divisible by 13? " + divTest(num, 13));
    System.out.println("Is the number divisible by 77? " + divTest(num, 77)); 
    System.out.println("How many times does 7 appear in the number? " + digitAppearances(num, 7));
    System.out.println("How many times does 3 appear in the number? " + digitAppearances(num, 3));

public static int digitAppearances(int num, int x) {

    // Check if num is 0
  if (num <= 0 ) {
    return 0;
  }

// Count number of times x appears
else if (num % 10 == x) {
    return 1 + digitAppearances(num / 10, x);
}
else {
    return digitAppearances(num / 10, x);
}
}
3
  • That code cannot throw InputMismatchException Commented Apr 3, 2018 at 22:53
  • An InputMismatchException is thrown by a Scanner, but I don't see one here. Please post the code that actually throws that exception. Commented Apr 3, 2018 at 22:53
  • My apologies, it is there now. Commented Apr 3, 2018 at 22:55

1 Answer 1

1

The Scanner is attempting to read an int with the nextInt method.

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

  • nextInt(radix):

Throws:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

If you enter a value larger than Integer.MAX_VALUE (about 2.1 billion, 10 digits), then you will get an InputMismatchException.

If you want to enter up to 19 digits, use nextLong.

If you want to enter an arbitrary number of digits, just call next, get the string, and validate that it only contains digits. You'll need to convert the character digits to a numeric type before further processing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.