Вы должны поставить эти две строки -
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r);
внутри блока try
-
import java.util.Scanner;
import java.io;
/**
*
* @author Osugule
*/
public class AreaCircle
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner sc = new Scanner(System.in); // read the keyboard
System.out.println("This program will calculate the area of a circle");
boolean correct_input = false;
while(correct_input == false)
{
System.out.println("Enter radius:");//Print to screen
try
{
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r);
String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle is " + area);
correct_input = true;
}
catch( NumberFormatException e )
{
System.out.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
catch( InputMismatchException e )
{
System.out.println("Input Mismatch, please enter a number");
//put a message or anything you want to tell the user that there is an
//input mismatch.
}
}
}
}
Из документации -
public double nextDouble ()
Сканирует следующий токен ввода как двойной. Этот метод вызывает исключение InputMismatchException, если следующий токен не может быть преобразован в допустимое значение типа double Если перевод выполнен успешно, сканер продвигается дальше соответствующего ввода.
Выдает
InputMismatchException - если следующий токен не соответствует регулярному выражению Float,
или вне диапазона.
NoSuchElementException - если ввод исчерпан
IllegalStateException - если этот сканер закрыт
Так что, если вы введете недопустимый символ, sc.nextDouble()
, вероятно, выдаст InputMismatchException
, который не будет пойман блоком catch
, потому что он только ловит NumberFormatException
. Таким образом, ваша программа завершит работу после выдачи исключения, но вы не получите никаких сообщений.
Чтобы справиться и с этим сценарием, добавьте следующий блок под текущим блоком catch
-
catch( NumberFormatException e )
{
System.out.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
// New catch block
catch( InputMismatchException e )
{
System.out.println("Input Mismatch, please enter a number");
//put a message or anything you want to tell the user that there is an
//input mismatch.
}