Какую ошибку вы обнаружите в этом коде / программе?Erro это не будет работать, если вы не наберете число - PullRequest
2 голосов
/ 18 марта 2012

Итак, мой вопрос по этому вопросу: Эта программа должна рассчитывать площадь круга пользователь вводит число выходит с ответом также недопустимы любые неверные данные, я использую try-catch, но это не сработает ...

Огромное спасибо всем за ваше время :))

Вот код:

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");
System.out.println("Enter radius:");//Print to screen
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r); 
try {

}
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.
}

String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle  is " + area);

    }
}

Ответы [ 3 ]

0 голосов
/ 18 марта 2012

Я отредактировал ответ, чтобы он снова спросил пользователя, введен ли неправильный ввод

Вы должны поместить nextDouble в предложение try:

boolean inputProcessed = false;
while (!inputProcessed) {
    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);
        // this indicates that we were able to process the input, and we should stop now.
        inputProcessed = 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.
    }
}

Обратите внимание, что я добавил строку после try-catch в предложение try, так как если вам не удалось разобрать число, они не должны печататься.

0 голосов
/ 18 марта 2012

Вы должны поймать InputMismatchException исключение следующим образом:

import java.util.InputMismatchException;
import java.util.Scanner; 
public class AreaCircle { 
    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");
        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);

        }
        catch( InputMismatchException 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( 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.
        }
    }
}
0 голосов
/ 18 марта 2012

Вы должны поставить эти две строки -

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.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...