Java 如何在代码中添加或使用While循环
我想使用while循环,以便它可以捕获任何无效输入,如字母或随机%$@…等 我是java新手……非常感谢你们的帮助:) 以下是我的工作:Java 如何在代码中添加或使用While循环,java,Java,我想使用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("Thi
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
将抛出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;
}
就个人而言,我不会使用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循环中。希望这能奏效 至少告诉我们你试过使用while循环。堆栈溢出不是一个代码工厂。你可能应该尝试用谷歌搜索它,看看这里:@user1190386:发生了什么错误?你包括导入语句了吗?好的,我这样做了…但是程序不会运行…在网络bean和终端上什么都没有出现?
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....
}
try {
double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
//put a message or anything you want to tell the user that their input was weird.
}