Как реализовать цикл while в этом фрагменте кода? - PullRequest
1 голос
/ 18 марта 2012

Моя программа заканчивается после ввода неверного ввода. Я знаю, что мне нужно использовать цикл while, чтобы пользователь вводил число.

Вот код:

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

Ответы [ 3 ]

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

put double r = sc.nextDouble (); и исключение внутри цикла while.

поместите пользовательское сообщение внутри блока перехвата исключений, например «Ввод неправильный, введите ввод еще раз. Если возникнет исключение во время выполнения цикла.

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

Тебе скорее нужен цикл do-while. Вы используете цикл do-while, где блок кода в цикле должен выполняться хотя бы один раз. Вот как вы его реализуете:

import java.util.InputMismatchException;
import java.util.Scanner; 
public class Circle { 
    public static void main(String[] args) {

          boolean invalid_input = false;    

        do
        {
        // 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);
                invalid_input = false;

        }
        catch( NumberFormatException e ) {
              invalid_input = true;
            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 )
        {
                invalid_input = true;
            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.
        }
        }while(invalid_input== true);



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

Просто сделайте бесконечный цикл вокруг части, которую вы хотите продолжать делать, пока не получите действительный ввод, и если вы получите действительный ввод, разбейте его.

while (true){
  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);
    break;                              <---- New code that will break the loop

  }
  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.
  }
}
The execution will continue from here after break 
...