简体   繁体   English

继续进行循环,直到用户输入正确的输入类型为止?

[英]Continued for-loop until user enters correct kind of input?

I am supposed to write a program that asks the user for 5 non-negative integers and then displays the sum of these integers. 我应该写一个程序,要求用户输入5个非负整数,然后显示这些整数的总和。 Also if the user enters a non-integer value, I have to keep asking until the user has inputted 5 acceptable values. 另外,如果用户输入非整数值,则我必须不断询问,直到用户输入了5个可接受的值。

How do I do this using non-nested for statements?? 我该如何使用非嵌套的for语句呢? Thanks!!! 谢谢!!!

This should work for you. 这应该为您工作。 It continues to scan until the user has typed an integer. 它将继续扫描,直到用户键入整数为止。

    Scanner scan = new Scanner(System.in);
    int sum = 0;

    for(int i = 0; i < 5; i++)
    {

    System.out.println("Enter integer value: ");
    while (!scan.hasNextInt())
    {
        System.out.println("That's not a number, try again: ");
        scan.next();
    }
    sum += scan.nextInt();
    }
    System.out.println(sum);

Use a while() loop. 使用while()循环。

int sentinel = 0;
Scanner s = new Scanner(System.in);
int sum = 0;

while (sentinel < 5 && s.hasNextInt()){
  int num = s.nextInt();
  if(num>=0){
    sum += num;
    sentinel++;
  }else
    System.out.println("That wasn't a non-negative int :(");
}

And then just print out the sum. 然后只打印出总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM