Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Rejecting certain inputs

  1. #1
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Rejecting certain inputs

    Any ideas of how I could reject character input when i ask the user for an integer?
    Example

    If i want him to enter age... It won;t let him spell it out with characters.

    Best Regards

    --- Update ---

    Example:

     
    System.out.println("")
    System.out.print("SubjectNumber : ");
    int subjectNum = sc.nextInt();

    I want to allow the user to input only a number


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    I don't know any way to stop a user from entering whatever he wants. The program can refuse to accept what is entered and ask the user to enter what the program wants. This can be done repeatedly until the user enters what is desired or quits trying.

    What does the code you posted do when the user enters something other than a number?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    If you enter say, a string, the program crashes. Is there a way to control what happens if a different data type is entered?

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Rejecting certain inputs

    If you were using a GUI instead of the command prompt, there would be a handful of ways to do this.

    As for preventing the program from crashing, use and if statement and the Scanner's hasNextInt() method to check if the input was an int before calling the nextInt() method.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    Haven't learnt GUI's in Java yet!

    Could you give me an example of what you mean?

    Thanks!

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    Put the code that causes the exception inside a try{}catch block. The catch block code will get control if an exception is thrown.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Rejecting certain inputs

    You could do what Norm said, but a potentiality "better" solution (because it does not require the creation of exceptions) would be to do something like this:
    if(sc.hasNextInt()) {
         int subjectNum = sc.nextInt();
         ... // Continue with program or whatever
    }
    else {
         ... // Do something if the input isn't an int
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #8
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    So this will just let me show an error right? i cannot really loop back... i think

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    Put the code in a while() loop that continues looping UNTIL the user enters the desired input.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

     
    public static int studentNumberEntered(int number, Scanner sc) {
         int numberEntered = 0; 
         sc.reset();
         try { 
          System.out.print("Student Number: ");
          numberEntered = sc.nextInt();
     
          sc.nextLine();
        }
        catch (Exception E) {
          studentNumberEntered(number, sc);
        }

    Im trying to to a method call in the catch so if something else is entereed, the method will be called again.

    The problem is im getting a stack overflow error o.O

    Any ideas?

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    getting a stack overflow error o.O
    That is probably because of the recursive call:
       studentNumberEntered(number, sc);

    Use a loop instead of a recursive call.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Rejecting certain inputs

    You are getting a stack overflow because of infinite recursion (a method calling itself forever with no exit-case). This would be occurring if your catch block is always being hit. My guess would be that it is constantly reevaluating the input, and constantly failing.

    I am actually a little surprised you can even run that code. It shouldn't compile, since it doesn't appear you ever return a value from the method.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  13. #13
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    it was because of the integer parsing

    Solution

     
     public static int numberEntered = 0;
        public static int studentNumberEntered(Scanner sc) {
     
        try { 
          System.out.print("Student Number: ");
          numberEntered = Integer.parseInt(sc.nextLine());
          numberEntered = numberCheck(numberEntered, sc);
        }
        catch (Exception E) {
          System.out.println("------------");
          System.out.println("   ERROR    ");
          System.out.println("------------");
          System.out.println("");
          studentNumberEntered(sc);
        }
        return numberEntered;
       }

    Thanks Norm and aussiemcgr

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    The code still has the recursive call. That should be removed and a loop used instead.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Rejecting certain inputs

    A potential change to your current code (so numberEntered stays within the scope of the method):
    public static int studentNumberEntered(Scanner sc) {
    	int numberEntered = 0;
    	try { 	
    		System.out.print("Student Number: ");
    		numberEntered = Integer.parseInt(sc.nextLine());	
    		numberEntered = numberCheck(numberEntered, sc);
    	}	
    	catch (Exception E) {
    		System.out.println("------------");
    		System.out.println("   ERROR    ");
    		System.out.println("------------");
    		System.out.println("");
    		numberEntered = studentNumberEntered(sc);
    	}
    	return numberEntered;
    }

    This is assuming you want the recursive call. A loop could just as easily be used, as Norm suggested.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  16. #16
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    what are the benfits of a loop from a recursive call?

    and any idea how i can apply the same concepts to a array, with 2 outputs?

     
    double [] homeworkMark  = new double[amountAssignment];
          double [] examinationMark  = new double[amountAssignment];
          for (int i = 0; i <= amountAssignment-1; i++ ) {
              System.out.print("Homework Mark for Assignment " +(i+1) + ": ");
              homeworkMark[i] = sc.nextInt();
              System.out.print("Examination Mark for Assignment " + (i+1) + ": ");
              examinationMark[i] = sc.nextInt();
          }

  17. #17
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    any ideas?

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    apply the same concepts to a array, with 2 outputs?
    Sorry I don't understand your question.
    An array can hold many values.

    What do you want the method to do?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member melki0795's Avatar
    Join Date
    Nov 2013
    Location
    Malta
    Posts
    49
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Rejecting certain inputs

    is it possible to put an array in a method, and have the same recursion call? how would the variable be returned in that case?

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,089
    Thanks
    52
    Thanked 2,284 Times in 2,255 Posts

    Default Re: Rejecting certain inputs

    If an array is defined inside of a method, it can be passed as an arg to another method that is called from that method:
    void aMethod() {
      int[] anArray = {1};      // define an array in this method
      int valReturned = methodToCall(anArray); //  pass local array to another method
    }
    int methodToCall(int[] array) {  // receive an array
       return 0;    //  return an int
    }
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Rejecting certain inputs

    what are the benfits of a loop from a recursive call?
    For your purposes, yes, because a loop is more simple and easier to understand (as well as a handful of other reasons around complexity).
    In my experience, recursion is most powerful when you are attempting to implement a brute-force algorithm where you want to be able to "undo" calculations if the chosen path fails to reach the end-goal. It isn't "undo" in the sense that you are probably thinking. Rather, recursion "remembers" the place of all previous recursion iterations. So if you were designing a game or something where a computer-controlled bot solves a maze, the brute-force approach of doing that would be to use recursion, because it allows the bot to back-track if it reaches a dead-end.

    Beware of using recursion if you are attempting to modify primitives in an array. Changes you make to primitives in later recursion iterations will not change the values in the array in previous recursions. This is true for primitives because of something called mutability.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Password Inputs
    By 0w1 in forum Java Theory & Questions
    Replies: 1
    Last Post: July 19th, 2013, 02:33 AM
  2. Need Help With Jtextfield inputs and Textfiles
    By Notoriousdk in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 31st, 2013, 06:35 AM
  3. Concatenating Inputs, need help please!
    By xdrechsler in forum File I/O & Other I/O Streams
    Replies: 17
    Last Post: August 19th, 2011, 01:02 PM
  4. How to store 10 inputs in an arraylist?
    By Bray92 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 20th, 2011, 10:22 PM
  5. Inputs not being applied.
    By Norflok669 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 15th, 2010, 12:25 AM