我正在创建一个程序,在交互式输入结束后打印出情况摘要(ctrl -d)。因此,它打印了交互输入后接种疫苗的儿童的平均年龄和百分比的摘要。
然而,每当我按名称:ctrl-d时,我总是收到No Line Found错误。我的编译器告诉我错误是在name = sc.nextLine();在while循环中,但我不知道究竟是什么导致了错误。
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
答案 0 :(得分:0)
如果你问我,你没有正确地为你的循环实现退出条件。
尝试这样的事情:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
这样您就可以退出输入新人,而无需输入可能导致错误的奇怪命令。此外,do-while
循环可帮助您减少代码,因为您不必两次使用相同的代码,即示例中Scanner sc = new Scanner(System.in);
和while(sc.hasNextLine())
之间的所有代码。