如何在我的代码中添加或使用While循环

时间:2012-03-17 16:46:15

标签: 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("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);

    }
}

4 个答案:

答案 0 :(得分:0)

在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;
  }
}

答案 1 :(得分:0)

如果输入无效,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);

答案 2 :(得分:0)

处理用户输入非常简单......

我最近有一个检测无效用户输入的程序......

以下是我使用循环执行的操作:

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

答案 3 :(得分:0)

就个人而言,我不会使用while循环,我会使用try / catch异常处理程序。你可以在它周围放一个while循环,但我不确定你为什么会这样做。有一个内置的异常,叫做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循环。希望这有效!