如何确保用户输入正确的坐标值?

时间:2016-06-04 18:58:14

标签: java

所以我有一个具有Point类的合成程序,并且在Line类中使用Point类isValid方法,以确保用户在继续之前输入正确的值。

基本上,当他们输入我的主要课程enterLine()中的值时,他们必须继续输入,直到它满足Point中的isValid()和Line中validateLine()的规则。

// This method is in the Point class and will be used by validateLine()
public static boolean isValid(int x, int y) 
{
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
  int maxHeight = screenSize.height; 
  int maxWidth = screenSize.width;

  if (x < 0 || y < 0 || x > maxWidth || y > maxHeight)
  {
     return false;
  }
  return true;
}


 // This method is in the Line class, uses isValid() from Point Class
public static boolean validateLine(int x1, int y1, int x2, int y2, int width)
{
    if (Point.isValid(x1, y1) && Point.isValid(x2, y2))
    {
        return true;
    }
    return false;
}


// This method is in main, it prompts user to enter two valid Points.
public static Line enterLine(int line, Scanner kb)
{
  System.out.println("Please enter two x's and y's values, a width, and color");
  int x1 = kb.nextInt();
  int x2 = kb.nextInt();
  int y1 = kb.nextInt();
  int y2 = kb.nextInt();
  int newWidth = kb.nextInt();
  String color = kb.next();


  return new Line(x1, x2, y1, y2, color, newWidth);

}

1 个答案:

答案 0 :(得分:0)

假设您正在询问如何反复提示用户输入xy值,如果它无效,那么您将使用do while或{{1循环。

你会做类似的事情:

while