如何清除Java中的扫描程序缓冲区?

我有这样的事情:

Scanner in=new Scanner(System.in); int rounds = 0; while (rounds  3) { System.out.print("How many rounds? "); if (in.hasNextInt()) { rounds = in.nextInt(); } else { System.out.println("Invalid input. Please try again."); System.out.println(); } // Clear buffer } System.out.print(rounds+" rounds."); 

我该如何清除缓冲区?

编辑:我尝试了以下内容,但由于某些原因它无效:

 while(in.hasNext()) in.next(); 

您无法明确清除扫描仪的缓冲区。 在内部,它可以在读取令牌之后清除缓冲区,但这是在porgrammers的范围之外的实现细节。

尝试这个:

 in.nextLine(); 

这使扫描仪进入下一行。

这应该解决它…

 Scanner in=new Scanner(System.in); int rounds = 0; while (rounds < 1 || rounds > 3) { System.out.print("How many rounds? "); if (in.hasNextInt()) { rounds = in.nextInt(); } else { System.out.println("Invalid input. Please try again."); in.next(); // -->important System.out.println(); } // Clear buffer } System.out.print(rounds+" rounds."); 

使用以下命令:

 in.nextLine(); 

之后

 System.out.println("Invalid input. Please Try Again."); System.out.println(); 

或者在下面的大括号之后(关于它的评论,是)。

此命令使扫描器前进到下一行(当从文件或字符串中读取时,这只是读取下一行),因此在这种情况下基本上将其刷新。 它清除缓冲区并准备扫描仪以获得新输入。 当用户输入无效输入时(例如,当被要求输入数字时,它)可以用于清除当前缓冲区。

该方法的文档可以在这里找到: http : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

希望这可以帮助!

插入行

 in.nextLine(); 

试试这段代码:

 Scanner in=new Scanner(System.in); int rounds = 0; while (rounds < 1 || rounds > 3) { System.out.print("How many rounds? "); if (in.hasNextInt()) { rounds = in.nextInt(); } else { in.NextLine(); // to clear Scanner //You can throw new InputMismatchException(); System.out.println("Invalid input. Please try again."); System.out.println(); } } System.out.print(rounds+" rounds."); 

一种解决方案是将bank对象放在main中的do-while循环内,以便每次都创建一个新的bank对象。

然而,这提出了某些问题,即帐户数组和计数变量。 您可以通过将它们放在bankUser中来解决此问题。

 static int count = 0; //don't forget to make count global and initialize public static void main(String[] args) { int Choice; //place the Acct array inside bankUser main or declare //as global bankAcct myAcct[] = new bankAcct[3]; do { //Place the bank object inside the do-while Bank myBank = new Bank(count, myAcct); //pass the variables to the //new Bank object dispMenu(); Choice = getChoice(); proChoice(Choice, myBank); } while (Choice !=0); } 

不要忘记将count设为全局,因为它需要能够传递到main中的对象并且通过proChoice方法中的switch-case openAcct递增。

 case 1: myBank.openAcct(); count++; break; 

最后,您可以使用bank类中的构造函数将myAcct数组和count变量传递给对象。

 public Bank(int count, bankAcct myAcct[]) { this.count = count; this.myAcct = myAcct; 

}