2012-02-09 50 views
3

我怎么能说以下内容:虽然不是条件

while(input is not an int){ 
do this 
} 

我想这个代码,但我知道这是错误的:

int identificationnumber; 
Scanner sc3 = new Scanner(System.in); 
identificationnumber = sc3.nextInt(); 

while(identificationnumber != int){ // this line is wrong 

Scanner sc4 = new Scanner(System.in); 
identificationnumber = sc4.nextInt(); 

} 

任何建议please.Thanks。

+0

因此你得到一个int并且想检查它是否不是一个?那么还有什么呢? – guitarflow 2012-02-09 00:49:10

+0

http://stackoverflow.com/questions/2674554/how-know-a-variable-type-in​​-java – AJP 2012-02-09 00:50:47

回答

0

通过编写sc3.nextInt()我假设你总是得到一个int,所以检查一个非int看起来有点奇怪。

也许最好是返回一个字符串与数字里面。如果字符串是空的停止(您可以检查“”),否则将其转换为整数。

+0

我使用sc3.nextInt来获取输入到一个int变量。 – 2012-02-09 10:58:01

+0

一个hasNextInt方法确实是更好的解决方案。 – 2012-02-09 11:29:49

6

尝试:

while (! scanner.hasNextInt()) { // while the next token is not an int... 
    scanner.next();    // just skip it 
} 
int i = scanner.nextInt();  // then read the int 
0

使用nextInt()扫描器类的方法。

它抛出,

InputMismatchException - 如果下一个标记不匹配 Integer正则表达式,或者超出范围

1

你想这个?

String identificationnumber; 
Scanner scanner = new Scanner(System.in);//Only one Scanner is needed 

while (scanner.hasNext()) { // Is there has next input? 
    identificationnumber = scanner.next();//Get next input 
    try { 
     Integer.parseInt(identificationnumber);//Try to parse to integer 
     System.out.println(identificationnumber + " is a number!"); 
    } catch (NumberFormatException e) { 
     System.out.println(identificationnumber + " is not a number!"); 
    } 
} 
+0

感谢你 - 但它只是让我陷入无限循环。有没有一种方法可以用for循环做到这一点? – 2012-02-09 10:56:22

+0

@ayokunleadeosun如果你想打破循环,你可以定义一个结束标志字符串或只是使用“控制+ c” – plucury 2012-02-09 13:41:33