java - 用户应输入未定义数量的整数,然后将它们分成几组

标签 java if-statement

我是 Java 的新手,我一直在努力解决这个问题,任务是让用户在程序中输入未定义数量的整数,然后程序应该能够跳转然后打印出来每个类别中的整数数量。类别是大于 100、小于 100、等于 100 和整数总数的整数。当用户输入否定时 # 程序应该结束并打印出前面提到的类别。

我遇到的问题是 #1 并非所有用户输入都正确添加 #2 while 循环不会在负值处停止 # 但只要感觉合适就会停止,例如在 20 个不同的 # 之后。

我真的不知道我做错了什么。请帮助我。

这是代码:

public static void main(String[] args)
{
    int high = 0;
    int low = 0;
    int hundred = 0;
    int total = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter values, put a negative # to quit:");
    while (scan.nextInt() > -1)
    {
                if (scan.nextInt() > 100)
                 {
                     high++;
                     total++;
                 }
                else if (scan.nextInt() < 100)
                 {
                     low++;
                     total++;
                 }
                else if (scan.nextInt() == 100)
                 {
                     hundred++;
                     total++;
                 }
                 else
                 {
                     break;
                 }
    }
     System.out.println("Amount of # over 100: " + high);
     System.out.println("Amount of # under 100: " + low);
     System.out.println("Amount of # that equals 100: " + hundred);
     System.out.println("Total amount of # : " + total);

最佳答案

实际上,您在每次条件检查中都得到了输入,我认为您的代码是错误的。 试试这个....

public static void main(String[] args){
int high = 0;
int low = 0;
int hundred = 0;
int total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter values, put a negative # to quit:");
int number=0;
while ((number=scan.nextInt()) > -1)
{
            if (number> 100)
             {
                 high++;
                 total++;
             }
            else if (number < 100)
             {
                 low++;
                 total++;
             }
            else if (number == 100)
             {
                 hundred++;
                 total++;
             }
             else
             {
                 break;
             }
}
 System.out.println("Amount of # over 100: " + high);
 System.out.println("Amount of # under 100: " + low);
 System.out.println("Amount of # that equals 100: " + hundred);
 System.out.println("Total amount of # : " + total);

关于java - 用户应输入未定义数量的整数,然后将它们分成几组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49397717/

相关文章:

java - 将 MYSQL 日期时间值转换为 UTC 时区格式 yyyy-MM-dd'T'HH :mm:ss'Z'

python - 缩短 if 语句的序列

javascript - JavaScript 中的 if/if else 逻辑

php - 检查数组中的值

java - 当两者的输出相同时,为什么我的 if/else 语句不匹配?

java - 如何不在 catch block 中重复代码?

java - Spring Cacheable 实现类

java - 如何安全地读取可能是二进制的文本文件?

java - 如何减少 if 语句

java - Log4j 堆栈溢出错误