[英]How do i add the or use While loop in my code
我想使用while循环,以便它可以捕获任何无效输入,例如字母或随机%% $ @@ ...等
我是Java的新手...非常感谢你们的帮助:)这是我正在从事的工作:
import java.util.Scanner;
public class AreaCircle {
public static void main(String[] args) {
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);
String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle is " + area);
}
}
在nextDouble周围放置一个try-catch块...该文档描述了扫描仪抛出的内容: http : //docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextDouble%28%29
while(True) {
try {
do_parsing()
break;
} catch (EvilException e) {
continue;
}
}
如果输入无效,则nextDouble
将抛出InputMismatchException
。 您可以将代码围绕在do / while循环中,在该循环中捕获异常并在收到有效输入后中断循环。
boolean error = false;
do {
try {
System.out.println("Enter val: ");
Scanner kbd = new Scanner(System.in);
double r = kbd.nextDouble();
error = false;
} catch (InputMismatchException e) {
error = true;
}
}while(error);
处理用户输入非常简单...
我最近有一个检测无效用户输入的程序...
这是我使用循环执行的操作:
static String[] letters = {"a","b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"};
//declare an array of letters or number for your case
//and make a method to check if input key is present at the array..
public int getIndexOf(char key){
int charindex = -1;
for(int index=0; index<letters.length; index++){
if(symbols[index] == key){
charindex = index;
}
}
return charindex;
}
然后输入://这样就可以遍历输入
boolean sentinel = false;
char[] numbervalue= input.getText().toString().toCharArray();
for (int z = 0; z < numbervalue.length; z++) {
int m = bal.getIndexOf(plaintext[z]);
if(m == -1){
sentinel = false;
break;
}
}
然后您可以进行检查...
if(sentinel){
//prompt the user that the input contains invalid characters
}else{
//continue with the processing....
}
就个人而言,我不会使用while循环,而会使用try / catch异常处理程序。 您可以绕一会儿循环,但是我不确定为什么会这样做。 有一个称为NumberFormatException的内置异常,它是针对像您所说的错误之类的。 所有你要做的就是
try {
double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
//put a message or anything you want to tell the user that their input was weird.
}
从字面上看,它所要做的就是,如果输入的内容不是数字,则进入catch块并打印您的消息。 如果愿意,可以将所有内容放入while循环中,以进行while循环。 希望这有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.