我如何只采用整数输入(只有扫描类和if和else语句或while循环,如果可能的话 - 没有布尔值)?

时间:2014-04-13 20:12:03

标签: java loops integer

这是我到目前为止的代码:

import java.util.Scanner;
public class Whatever{
    public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("How many pigs are there?");
    int number = Integer.parseInt( keyboard.nextLine() );
    int continueProgram = 0
    while(continueProgram == 0)
        {
            if (number>= 0 && number <= 32767)
            { do this;
                      continueProgram++;
            }else{
                     do this;
            }

我必须使用integer.parseInt才能使我的其余代码工作,所以我无法改变它。有什么办法只采取整数而不是字母?我的代码产生错误,因为如果我输入一个字母,parseInt将产生红色错误,而不是输出类似&#34的字符串;再试一次。请输入数字&#34;或类似的东西。

2 个答案:

答案 0 :(得分:2)

您需要使用try catch这样的

来包围您的parse.int
int number = 0; // you need to initialize your variable first
while (true) {
    try {
    number = Integer.parseInt(keyboard.nextLine());
    break; // this will escape the while loop
    } catch (Exception e) {
    System.out.println("That is not a number. Try again.");
    }
}

答案 1 :(得分:1)

试试这个:

 Scanner keyboard = new Scanner (System.in);
 System.out.println("How many pigs are there?");
 if(keyboard.hasNextInt()) {

   int number =  keyboard.nextInt();        

   }else{ 
        System.out.println("Not an integer number!");
        keyboard.next();
   }