2015-12-07 48 views
-2

这是我正在使用的程序,需要4个int并找到它们的区域。我需要把一个异常,检测用户是否不输入一个int和一个字符串。我想它(“仅数字”)告诉用户我该如何处理这个程序中的异常?

package areacircle; 
import java.util.Scanner; 
public class AreaCircleTwoPointO { 

public static void main(String[] args) { 
Scanner reader = new Scanner (System.in); 
    System.out.print ("Type The x1 point please: "); 
    int x1 = reader.nextInt(); 
    System.out.print ("Type The x2 point please: "); 
    int x2 = reader.nextInt(); 
    System.out.print ("Type The y1 point please: "); 
    int y1 = reader.nextInt(); 
    System.out.print ("Type the y2 point please: "); 
    int y2 = reader.nextInt(); 
    double area = areaCircle(x1, x2, y1, y2); 
    System.out.println ("The area of your circle is: " + area); 
} 
    public static double distance 
      (double x1, double y1, double x2, double y2) 
{ 
    double dx = x2 - x1; 
    double dy = y2 - y1; 
    double dsquared = dx*dx + dy*dy; 
    double result = Math.sqrt (dsquared); 
    return result; 
} 

public static double areaCircle(double x1, double y1, double x2, double y2) 
{ 
    double secretSauce = distance(x1, y1, x2, y2); 
    return areaCircleOG(secretSauce); 
} 

public static double areaCircleOG(double secretSauce) 
{ 
    double area = Math.PI * Math.pow(secretSauce, 2); 
    return area; 
} 
} 

我的有些想法会像这里是..

public static int getPoints() 
    { 
    int age = -1; 
    boolean continueLoop = true; 

    while (continueLoop) 
    { 
     String inputStr = JOptionPane.showInputDialog("Enter point x1: "); 
     try { 
      age = Integer.parseInt (inputStr); 
      continueLoop = false; 
     } 
     catch (NumberFormatException e) 
     { 
      JOptionPane.showMessageDialog(null, "Age must be an integer!!"); 
     } 
    } 
    return age; 
} 

,但关于这个事情是,它使用JOptionPane和我不想使用JOptionPane,只是扫描仪。

+0

你想用扫描仪显示的消息?这没有意义。 – Stultuske

+0

请澄清你的问题。你想如何显示错误信息? – WIR3D

+1

如果您不想使用消息框,您将打印出控制台。读取int = reader.nextInt()的行;如果输入不是数字,将会抛出异常。将该调用放入返回值的某个方法中,并在try/catch中调用该调用。尝试从用户那里获取输入,但尚未获得有效输入。 –

回答

0

您可以使用下面的代码:

public static void main(String[] args) 
{ 
    Scanner reader = new Scanner (System.in); 

    boolean finished = false; 
    while(!finished) 
    { 
     try 
     { 
      System.out.print ("Type The x1 point please: "); 
      int x1 = reader.nextInt(); 
      System.out.print ("Type The x2 point please: "); 
      int x2 = reader.nextInt(); 
      System.out.print ("Type The y1 point please: "); 
      int y1 = reader.nextInt(); 
      System.out.print ("Type the y2 point please: "); 
      int y2 = reader.nextInt(); 
      double area = areaCircle(x1, x2, y1, y2); 
      System.out.println ("The area of your circle is: " + area); 
      double area = areaCircle(x1, x2, y1, y2); 
      System.out.println ("The area of your circle is: " + area); 
      finished = true; 
     } 
     catch(NumberFormatException e) 
     { 
      System.out.println("Please type in a number! Try again."); 
     } 
    } 
} 
+0

非常感谢你 minecrafter338这完全回答了我的问题 –

相关问题