2012-03-17 102 views
0

我想使用while循环,因此它可以捕获任何无效的输入,如字母或随机%% $ @@等等如何添加或在我的代码中使用While循环

Im new to java ......对于很多球员乌尔THANKS帮助:) 这里是林工作:

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); 

    } 
} 
+2

至少告诉我们你试过使用while循环。堆栈溢出不是代码工厂 – 2012-03-17 16:49:13

+1

您应该尝试谷歌它,看这里: http://www.java2s.com/Code/Java/Development-Class/Howtoreadfromstandardinput.htm – 2012-03-17 16:49:45

回答

0

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

是的,我试过我得到一个错误的“catch(InputMismatchException e)”部分.. – 2012-03-17 17:18:11

+0

@ user1190386:什么是错误?你是否包含进口报表? – blackcompe 2012-03-17 17:54:58

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

就个人而言,我不会用一个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循环中。希望这个作品!

+0

好的,所以我做到了....但程序不会运行......没有什么出现在净豆和终端? – 2012-03-18 09:05:47