-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,只是掃描儀。
你想用掃描儀顯示的消息?這沒有意義。 – Stultuske
請澄清你的問題。你想如何顯示錯誤信息? – WIR3D
如果您不想使用消息框,您將打印出控制檯。讀取int = reader.nextInt()的行;如果輸入不是數字,將會拋出異常。將該調用放入返回值的某個方法中,並在try/catch中調用該調用。嘗試從用戶那裏獲取輸入,但尚未獲得有效輸入。 –