2014-07-13 49 views
0

我正在编写一个程序,其中包含一个测试,以确定用户输入是否为正整数,并在条目为非整数或负数时显示错误消息。如果输入非整数,我的代码将显示预期的错误消息,但只有在输入负整数时才会再次提示输入正整数。我试着添加:使用具有do-while循环的hasNextInt,没有负整数的错误消息

if (n <= 0); 
System.out.print("You have not entered a positive integer"); 

n = input.nextInt(); 

但让即使进入了一个正整数的错误信息出现。

我也曾尝试:

while (!input.hasNextInt() && n <= 0) 

任何帮助表示赞赏。

 Scanner input = new Scanner(System.in); 
     int n = 0; 

     do { 
     System.out.print("Please enter a positive integer: "); 
     while (!input.hasNextInt()){ 
      System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: "); 
      input.next(); 
     } 
     n = input.nextInt(); 

     } while (n <= 0); 

回答

1

试试这个:

int n = -1;//<-- it won't allow user to skip the loop after first pass without proper input 
do { 
    System.out.print("Please enter a positive integer: "); 
    try { 
     n = input.nextInt();//<-- in one pass ask input from user only once 
     if(0 > n) { 
      System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: "); 
     } 
    } catch (NumberFormatException ex) { 
     System.out.println("Invalid number !"); 
     break;//<-- break loop here, if don't wana prompt user for next input 
    } catch(java.util.InputMismatchException ex) { 
     System.out.println("Oops number is required !"); 
     break;//<-- break loop here, if don't wana prompt user for next input 
    } 
} while (n <= 0); 
+0

异常是太大的例外在这里使用,只是使用NumberFormatException。 –

+0

我试过这个,当输入一个非整数时会得到一个无限循环。 –

+0

@Arvind,谢谢!这工作! –

0

试试这个:

int n = -1; 
while (input.hasNextInt() && (n = input.nextInt()) < 0) 
{ 
    // print error message about negative number 
} 

循环退出时,如果 'N' 仍然是-1你必须输入,例如结束用户根据平台输入ctrl/d或ctrl/z。

如果用户在控制台,您可能还需要跳到行尾。

+1

我试过这个,当输入正整数时程序没有运行。 –

+0

“没跑”的意思是什么?只要输入正数,它就会跳出上面的循环。 – EJP

+0

它提示输入一个正整数,但是当输入一个正整数时,它没有跳出循环并打印结果。 –

相关问题