当值超过给定数字时,如何使用while或for循环进行计数?

时间:2017-06-10 04:10:38

标签: java loops for-loop while-loop

这是我的工作 我有一个问题是,如果他们的重量增加到总乘客重量超过承载能力,则不应计算最后一名乘客。

感谢。

import java.util.*;
public class Exam2
{   
    public static void main(String []args)
    {
        int inputmax ;
        int inputweight;
        int thesum = 0;
        int count =0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter maximum of weight: ");
        inputmax = sc.nextInt();
        while(inputmax < 1 )
        {
        System.out.println("Enter positive number of maximum of weight: ");
        inputmax = sc.nextInt();
        }
       while(thesum < inputmax)
       {
           System.out.println("Enter each of weight: ");
           inputweight = sc.nextInt();

           while ( inputweight < 0)
            {
            System.out.println("Enter positive number of weight: ");
            inputweight = sc.nextInt(); 
            }
            thesum += inputweight;
            count++;   
        }
        System.out.println("Number of people could carry is: " + count);
    } 
} 

2 个答案:

答案 0 :(得分:1)

while(thesum < inputmax) {
    System.out.println("Enter each of weight: ");
    inputweight = sc.nextInt();

    while (inputweight < 0) {
        System.out.println("Enter positive number of weight: ");
        inputweight = sc.nextInt(); 
    }

    // Check if the the total of weight is greater than the maximum before adding the weight of last passenger into the sum
    if (thesum+inputweight < inputmax)
        thesum += inputweight;
        count++;
    } else {
        break;
    }
}

答案 1 :(得分:0)

这非常简单

您需要在代码中附加一张支票

 while(thesum < inputmax)
       {
           System.out.println("Enter each of weight: ");
           inputweight = sc.nextInt();

           while ( inputweight < 0)
            {
            System.out.println("Enter positive number of weight: ");
            inputweight = sc.nextInt(); 
            }
            thesum += inputweight;
            if((thesum >= inputmax)
            break;  // don't increase the count
            count++;   
        }

`