void searchForPopulationChange()
{
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
}
}}
你好!我正在研究一种方法,它将接受用户的输入,比方说(5000),并使用这些相应的数字搜索数据文件。并返回相应的号码和它所对应的县。
但是,我能够让这段代码运行以返回正确的值,但是当我输入一个“不正确”的值时,我无法让它运行。
有什么建议吗?谢谢!
发布于 2013-07-19 09:05:48
这有点不清楚,但我想如果输入不正确(不是整数),您想要一些东西来处理吗?使用hasNextInt,这样您将只捕获整数。
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
int num = scanner.nextInt();这将继续循环输入,直到它是一个有效的整数。您可以在循环中包含一条消息,提醒用户输入正确的数字。
如果您的数字在数组中没有匹配项,如果您想要显示一些内容,只需在您的for块后面添加代码(如果为found == false )。例如:
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}由于found仍然为false,因此while循环开始工作,并再次打印请求输入的行。
编辑:由于将这两个概念添加到代码中似乎有问题,下面是整个函数:
void searchForPopulationChange() {
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
input = scanner.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
}
}https://stackoverflow.com/questions/17736510
复制相似问题