Page 1 of 3 123 LastLast
Results 1 to 20 of 44
  1. #1
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default Error if someone enters the wrong data type

    Hello,

    I have a program that is currently accepting 4 different integers from a user. However, I need to put limit to the digit value the user can input, also if the user inputs a character, or a string, in other words, the wrong data type, the program shows an errors and asks the user to try again.

    The first integer would be between 1 and 40
    The second integer would be between 1 and 20
    The third integer can be between 1 and the highest value of the first integer
    The fourth integer can be between 1 and the highest value of the second integer

    I have been trying to use the "input.hasnextInt" but I'm honestly lost.

    Here is what my input fields look like:

    Scanner input = new Scanner(System.in);
    System.out.print("The X co-ordinate: "); // the x-axis location on the graph
    int x = input.nextInt();

    System.out.print("The Y co-ordinate: "); // the y-axis location on the graph
    int y = input.nextInt();

    System.out.print("Please enter a width for your rectangle: "); // the width of the rectangle to be plotted
    int width = input.nextInt();

    System.out.print("Now enter a height for your rectangle: "); // the height of the rectangle to be plotted
    int height = input.nextInt();
    Can anyone guide me in the right direction to start this? Should I use the input.hasnextInt within java, and if so, how is it implemented?

    I keep getting errors!

  2. #2
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    I ran your code with no problems. If you enter an illegal value (i.e. a non-integer), Java throws an exception.

    If you want your own custom error message, wrap your calls in a try-catch block. Catch the exception that is thrown, and output your own message. Also, make sure to place your input requests in a loop, so that the loop continues until the user inputs valid data.


    To make sure the input is in the bounds you want, add checks - make sure the input is in the range you want. If one of them fails, you could throw an exception (and catch it in your catch block).


    Using this method, the exception is throw on the invalid input - if "x" is invalid, no use asking for "y". The catch block will handle outputting the "error message" you want. And, by throwing it all in a loop, you'll continue until the user inputs valid data.

    Afterwards, you can continue with your code.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  3. #3
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Hey CodesAway,

    thank you so much for that, But I cannot use try and catch because I have no idea how to use it! :(

    Here is what I did so far and it seems to work for the most part
    int x;

    System.out.print("The x co-ordinate: ");
    Scanner input = new Scanner(System.in);

    while (input.hasNext())
    {
    if (input.hasNextInt())
    {
    if (input.nextInt() > 40 || input.nextInt() < 0)
    {
    System.out.println("Wrong");
    System.out.print("Try again: ");
    }

    else
    break;
    }

    else
    {
    input.nextLine();
    System.out.println("This is not a valid value!");
    System.out.print("The X co-ordinate: ");
    }
    }

    x = input.nextInt();
    The only problem is, when I input anything between 0 and 40, the loop doesn't end. Can you check this and tell me what I'm doing wrong?

  4. #4
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    To learn try-catch blocks, check out the The Java Tutorials -> Exceptions.

    As for why your code is acting weird, it's because you are asking for three int values (highlighted in red). So, it's not that it's not exiting, but it's waiting for two more values after you enter the first.

    Java Code:
    int x;
    
    System.out.print("The x co-ordinate: ");
    Scanner input = new Scanner(System.in);
    
    while (input.hasNext()) {
    	if (input.hasNextInt()) {
    		if ([COLOR="Red"]input.nextInt()[/COLOR] > 40 || [COLOR="#ff0000"]input.nextInt()[/COLOR] < 0) {
    			System.out.println("Wrong");
    			System.out.print("Try again: ");
    		}
    		else
    			break;
    	}
    	else {
    		input.nextLine();
    		System.out.println("This is not a valid value!");
    		System.out.print("The X co-ordinate: ");
    	}
    }
    
    x = [COLOR="#ff0000"]input.nextInt()[/COLOR];
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  5. #5
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Can you please tell me how I would fix it in the code I have already supplied?

    This is for an assignment and we haven't even been taught try and catch, so I'm thinking the professor expects us to finish it based on what we know already.

  6. #6
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Your code works and does the job. Instead of calling nextInt three times to retrieve the "x" value, you should only call it once - storing the value and comparing the stored values to your range.

    By replacing the three calls with just one, your code works fine - I tested it.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  7. #7
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Hello Codesaway,

    The int x, first of all, should be int. Then, it should be between 0 and 40 value.

    Can you please clarify how I'm calling it three times? I understand based on your quoted message that there are three input.nextInt methods, however, if I remove the first two, then how will I be able to get the program to check whether the int x value is between 0 and 40?

  8. #8
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Quote Originally Posted by lithium002 View Post
    Hello Codesaway,

    The int x, first of all, should be int. Then, it should be between 0 and 40 value.

    Can you please clarify how I'm calling it three times? I understand based on your quoted message that there are three input.nextInt methods, however, if I remove the first two, then how will I be able to get the program to check whether the int x value is between 0 and 40?
    You should have one call to nextInt for each input value. This does not imply that your should remove the first two (You need to remove two calls, but this doesn't mean it's the first two).

    My hint was "you should only call it once - storing the value and comparing the stored values to your range."
    Last edited by CodesAway; 11-16-2009 at 09:08 AM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  9. #9
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Hello Codesaway,

    Can you please illustrate via sample code?

  10. #10
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Hello,

    So I used this code
    int x;

    System.out.print("The x co-ordinate: ");
    Scanner input = new Scanner(System.in);

    while (input.hasNext())
    {
    if (input.hasNextInt())
    {
    x = input.nextInt();
    if ( x > 40 || x < 0)
    {
    System.out.println("Wrong");
    System.out.print("Try again: ");
    }

    else
    break;

    }

    else
    {
    input.next();
    System.out.println("This is not a valid value!");
    System.out.print("The X co-ordinate: ");
    }
    }
    but now the int x cannot be identified by functions outside this one. It has become local :(

  11. #11
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Java Code:
    Scanner input = new Scanner(System.in);
    		
    System.out.println("Please input an integer: ");
    int value = input.nextInt();
    		
    if (value < 0)
    	System.out.println("You entered a negative number");
    else
    	System.out.println("You entered a positive number");
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  12. #12
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Quote Originally Posted by lithium002 View Post
    but now the int x cannot be identified by functions outside this one. It has become local :(
    I'm confused, it was a local variable beforehand as well. What are you trying to do with the value?
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  13. #13
    aaroncarpet's Avatar
    aaroncarpet is offline Senior Member
    Join Date
    Nov 2009
    Location
    California
    Posts
    147
    Rep Power
    0

    Default

    Java Code:
    try{ spinning my hard drive backwards ) catch(exception e){system.out.println("MY Virus Can't Control your hard or soft drive")}

  14. #14
    aaroncarpet's Avatar
    aaroncarpet is offline Senior Member
    Join Date
    Nov 2009
    Location
    California
    Posts
    147
    Rep Power
    0

    Default

    that gave ne a slider bar?

  15. #15
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    The code you provided won't work if the user inputs a character or a string.

    The assignment is to draw a graph of 40x20, and then ask the user to input four values, the x and y co-ordinates of the graph, and then to draw a rectangle in the x,y location of the user defined width and height.

    I have done all of that, except now I just need to make sure that the user inputted values are within the graph range i.e. between 40 and 0.

    The code I have written was meant to go on the following algorithm:

    First, the user inputs something
    The input goes into a loop
    Then, in the loop, the program checks whether the input was an Integer
    If it was, it checks whether it was in the range of 0 and 40
    If it isn't, it asks for the user to try again
    If it was, it is stored in a variable that can be used in other functions
    If the input was anything other than an integer, it asks the user to try again.


    Now I did all of that, except like you pointed out, when I run the program, if the value is within 0 and 40, the program doesn't go into the next command unless I press enter three times.

    If I stored the value only once, it becomes a local variable and I can't use it in other functions.

    Can you PLEASE help? I have spent almost 24 hours finishing this program and the past 6 hours on just figuring this out.

  16. #16
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Might I suggest putting this inside a method. Since each of your four inputs will look and behave the same, using a method makes the code clearer and easier to read.

    For example, a prompt method that prompts the user for a value, checks the value is in range, and shows error messages for incorrect/invalid input.

    Java Code:
    private static int prompt(Scanner input, String prompt, int rangeStart, int rangeEnd) {
    	// Your code goes here
    }
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  17. #17
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    This is how my code looks right now:

    Java Code:
    	private static void getInput() // ask for all the information you need from the user
    	{ 
    		int x;
    		
    		System.out.print("The x co-ordinate: ");
    		Scanner input = new Scanner(System.in);
    
    		while (input.hasNext())
    		{
    			if (input.hasNextInt())
    			{
    				x = input.nextInt();
    				if ( x > 40 || x < 0)
    				{
    					System.out.println("Wrong");
    					System.out.print("Try again: ");
    				}
    			}
    				
    			else
    			{
    				input.next();
    				System.out.println("This is not a valid value!");
    				System.out.print("The X co-ordinate: ");
    			}
    		}
    
    		System.out.print("The Y co-ordinate: "); // the y-axis location on the graph
    		int y = input.nextInt();
    	    
    		System.out.print("Please enter a width for your rectangle: "); // the width of the rectangle to be plotted
    		int width = input.nextInt();
            
    		System.out.print("Now enter a height for your rectangle: "); // the height of the rectangle to be plotted
    		int height = input.nextInt();
    	    
    		drawGraph(width, height, x, y); // now draw the graph by calling the function based on the variables

  18. #18
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Quote Originally Posted by lithium002 View Post
    The code you provided won't work if the user inputs a character or a string.
    It was AN EXAMPLE! I wasn't going to do your assignment for you. Especially since the code you had the first time works fine.


    Quote Originally Posted by lithium002 View Post
    If I stored the value only once, it becomes a local variable and I can't use it in other functions.
    FYI, It was local beforehand as well. And, yes, you can use it in other functions - pass the value as a parameter.

    Quote Originally Posted by lithium002 View Post
    Can you PLEASE help? I have spent almost 24 hours finishing this program and the past 6 hours on just figuring this out.
    I'm sorry, if my input isn't helpful, I can leave! Better yet, if you could tell me how you need help, that would make my job easier.

    You complain about all the code and advice I give you, but it works and runs fine - trust me, I already have a running copy that is a combination of the code presented. I just threw it into a method. I already can input ALL FOUR VALUES, using the code you have provided.

    So, if it's not working for you, or if you are not understanding it, please ask questions.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  19. #19
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Quote Originally Posted by lithium002 View Post
    This is how my code looks right now:
    ... code ...
    Is there a question??
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  20. #20
    lithium002 is offline Member
    Join Date
    Nov 2009
    Posts
    23
    Rep Power
    0

    Default

    Excuse me? I need help, I don't need anyone to finish my assignment. If I needed the former I wouldn't have spent this long trying to do it myself. :)

    I already explained what my problem is. I can't use prompt or catch and try or anything else because we haven't covered those things in our course.

    I'm having trouble with the code I already provided and need someone to tell me what I'm doing wrong. I know you're trying to help, I honestly appreciate it, but seriously, I'm not asking you to do my homework for me. That was arrogant and uncalled for in my opinion.

Page 1 of 3 123 LastLast

Similar Threads

  1. Error: unexpected type
    By silvia in forum New To Java
    Replies: 3
    Last Post: 02-05-2010, 10:54 PM
  2. Matlab data type implementation & speed
    By uzil24 in forum Advanced Java
    Replies: 3
    Last Post: 10-24-2009, 03:00 AM
  3. sychronized data type
    By java girl in forum Threads and Synchronization
    Replies: 3
    Last Post: 02-13-2009, 09:37 AM
  4. error while retrieving data from data base
    By kirtesh4u in forum New To Java
    Replies: 5
    Last Post: 11-15-2008, 05:10 PM
  5. Replies: 1
    Last Post: 11-11-2008, 09:18 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •