【发布时间】:2012-03-18 10:31:00
【问题描述】:
我的程序在我输入无效输入后结束。我知道我需要使用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.
}
}
}
【问题讨论】:
-
标识你想要重复的代码块;代码块应该在循环体内。确定您希望循环在什么条件下结束,这应该是被评估的 bool 表达式。可能有人会提出答案,但构建循环是非常基本的东西,我认为值得花时间自己学习。如果你在一个小时内仍然无法弄清楚,并且没有人回答你的问题,那么我很乐意自己提交一个例子=)
-
这与 Swing 没有任何关系。在将它们应用于问题之前,请仔细阅读标签。
-
你已经问过类似的问题here你自己尝试过什么吗??
标签: java loops java.util.scanner