Start New Discussion within our Software Development Community

Hello,

I've a program that asks a user for four different integer values, and then draws a rectangle on a graph based on those values.

I have done everything except now I need to set limits within the program so a user can only use valid values and I'm lost!

Here's how my function looks like right now:

private static void getInput() // ask for all the information you need from the user
	{ 
		Scanner input = new Scanner(System.in);    
		System.out.print("The X co-ordinate: "); // the x-axis location on the graph
		
		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
		
		// askAgain(); // ask if the user wants to make another rectangle
	}

I have heard that using the "input.hasnextInt" can be used when you have the java.util.Scanner for this, but I honestly cannot implement it.

I have tried this:

while (input.hasnext())
{
if (input.hasnextInt())
int x = input.nextInt();

else
System.out.println("Wrong data type! Try again");
System.out.print"(Enter the x co-ordinate: ");
}

I'm basically trying things here and there but I'm not getting anywhere.

Can anyone please guide me in the right direction?

If you have a file full of ints then you would just use

while(scanner.hasNextInt())

You would not use scanner.hasNext() and then the if statement, that is an extra unnecessary step. You could try something like

System.out.println("Enter an int");
while(scanner.hasNextInt()){
int i = scanner.nextInt();
System.out.println("Enter an int");
}
This article has been dead for over six months. Start a new discussion instead.