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

Java 当值超过给定值时,如何使用while或for循环计数?,java,loops,for-loop,while-loop,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;

这是我的工作 我有一个问题是,如果最后一名乘客的重量加在乘客总重量上超过了载客量,则不应计算最后一名乘客的重量

谢谢

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);
    } 
} 
这是相当琐碎的

您需要在代码中附加一个检查

 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++;   
        }

`

当前它有什么问题?在添加它之前,必须检查结果是否超过容量:if thesum+inputwweight>=inputmax{break;}else{thesum+=inputwweight;count++;}
 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++;   
        }