hi everybody..
i need help with my assignment.i want to display a error message saying that the user has inputed a string where an integer is needed.because when i enter "h" (for an example) in the x coordinate field the system crashes.i want to display an error message instead.
i need help with my assignment.i want to display a error message saying that the user has inputed a string where an integer is needed.because when i enter "h" (for an example) in the x coordinate field the system crashes.i want to display an error message instead.
Code:
/**
* A program that simulates an ant taking a step on a sheet of paper. stage 2
*
* @author (safra)
* @version (18/8/2010)
*/
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Stage2a
{
public static void main(String[] args)
{
final int WIDTH = 100; // width of the sheet in pixels
final int HEIGHT = 100; // height of the sheet in pixels
String input;
String input1;
int x; // the x-coordinate
int y; // the y-coordinate
int steps;// the number of steps to be taken
input = JOptionPane.showInputDialog ("Enter your ant's x-coordinate: ");
x = Integer.parseInt (input);
if(x < 0 || x > WIDTH-1) //checking if it's in the range
{
JOptionPane.showMessageDialog (null,"The x-coordinate must be between 0 and " + (WIDTH-1));
System.exit(-1);
}
input = JOptionPane.showInputDialog("Enter your ant's y coordinate: ");
y = Integer.parseInt(input);
if (y <0 || y > HEIGHT-1)
{
JOptionPane.showMessageDialog (null,"The y-coordinate must be between 0 and " + (HEIGHT-1));
System.exit(-1);
}
input = JOptionPane.showInputDialog ("Enter your ant's direction");
//the number of steps
input1 = JOptionPane.showInputDialog ("How many steps should the ant take?");
steps = Integer.parseInt(input1);
for (int z=1;z<=steps;z++)
{
if(input.equalsIgnoreCase("U"))//increasing or decresing the coordinates according to direction
{
y =++y;
}
else if (input.equalsIgnoreCase("UR"))
{
y =++y;
x =++x;
}
else if (input.equalsIgnoreCase("UL"))
{
y =++y;
x =--x;
}
else if (input.equalsIgnoreCase("R"))
{
x = ++x;
}
else if (input.equalsIgnoreCase("DR"))
{
y =--y;
x =++x;
}
else if (input.equalsIgnoreCase("D"))
{
y =--y;
}
else if (input.equalsIgnoreCase("DL"))
{
y =--y;
x =--x;
}
else if (input.equalsIgnoreCase("L"))
{
x =--x;
}
else
{JOptionPane.showMessageDialog (null,"Please enter one of the following: \n U,UR,UL,D,DR,DL,L,R");
System.exit (-1);}
}
// "Wrap" the x and y-coordinates if the ant has walked over the edge of the paper
if(x < 0)
{
x += WIDTH;
}
else if (x > WIDTH-1)
{
x=x-WIDTH;
}
if (y < 0)
{
y += HEIGHT;
}
else if (y > HEIGHT-1)
{
y=y-HEIGHT;
}
JOptionPane.showMessageDialog (null,"The new x coordinate is: " + x + "\n the new y coordinate is: " + y);
}
}
Comment