Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7972413
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:51:28+00:00 2026-06-04T07:51:28+00:00

Suppose I would like to add a method to Scanner called nextPositiveInt() which is

  • 0

Suppose I would like to add a method to Scanner called nextPositiveInt() which is similar to nextInt() except that when a negative integer is detected, a custom InputNegativeException is thrown.

Why would I want to do this when there are solutions that utilise hasNextInt()? While being a little less concise, it seems a whole lot tidier and more logical given the purpose of exceptions. For example:

Extended Scanner method:

Scanner cli = new Scanner(System.in);
boolean inputValid = false;

do
{
    System.out.println("Enter your age:");
    try
    {
        int age = cli.nextPositiveInt();
    }
    catch(InputNegativeException e)
    {
        System.out.println("You cannot specify a negative age.");
        inputValid = false;
    }
    catch(InputMismatchException e)
    {
        System.out.println("Your input must be numeric.");
        inputValid = false;
    }
} while(!inputValid);

hasNext() method:

Scanner cli = new Scanner(System.in);

do
{
    System.out.println("Please enter a positive number!");
    while(!sc.hasNextInt())
    {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    int number = sc.nextInt();
} while(number <= 0);

So assuming you aren’t already firing up a response telling me why this is a very bad idea (if it is, please do; I imagine there might be some objection regarding putting validation in Scanner) I’m confused about how to go about this. I guess I need to replicate the body of nextInt() in nextPositiveInt() with some minor changes? Can you even source the body of nextInt() anywhere?

I apologise that I have no code to show any effort I’ve made but I’m not sure where to start.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:51:30+00:00Added an answer on June 4, 2026 at 7:51 am

    Althought Scanner class is final and you cann’t extend it there exist another solution. You can use Delegation pattern.

    Also as Scanner class has all nessasary methods public you can easily copy original method and make a little change. See source code of Scanner class the only thing you should change is regexp used for matching string in order to exclude negative ints.

    Source code of scanner:

    public int nextInt() {
        return nextInt(defaultRadix);
    }
    
    public int nextInt(int radix) {
        // Check cached result
        if ((typeCache != null) && (typeCache instanceof Integer)
        && this.radix == radix) {
            int val = ((Integer)typeCache).intValue();
            useTypeCache();
            return val;
        }
        setRadix(radix);
        clearCaches();
        // Search for next int
        try {
            String s = next(integerPattern());
            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
                s = processIntegerToken(s);
            return Integer.parseInt(s, radix);
        } catch (NumberFormatException nfe) {
            position = matcher.start(); // don't skip bad token
            throw new InputMismatchException(nfe.getMessage());
        }
    }
    

    You should change only:

    String s = next(integerPattern());
    

    For you purposes you can hardcode regexp. Original regexp can easily be caught on debug.

    Definitely it wouldn’t be the best solution in terms of realization – a lot of code to write and many copy-paste, but it would be easy and nice to use.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I want to implement an interpreter for a functional language. I would like
Supposed I have a class called TrafficLight and I would like to have a
I suppose similar problem would have been discussed here, but I couldn't find it.
Suppose that you have to set 12 cookies, would it be better to store
Suppose I have a string that contains Ü. How would I find all those
suppose i have a sequence, called TEST_SEQ what would be the correct way of
I have a function that I use to add vectors, like this: public static
In Java, suppose I have a method that takes in two lists of integers,
Context: C# 3.0, .Net 3.5 Suppose I have a method that generates random numbers
Supposed I have the following string: string str = <tag>text</tag>; And I would like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.