No name
No name

Reputation: 29

How can I use while or for loop to count when value exceed the given number?

this my work I have a problem with the question is the last passenger should not be counted if their weight added to the total passenger weight exceeds the carrying capacity.

Thanks.

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

Upvotes: 0

Views: 92

Answers (2)

Isha Agarwal
Isha Agarwal

Reputation: 410

It's pretty trivial

You need to append one check to your code

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

`

Upvotes: 0

Sky
Sky

Reputation: 1433

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

Upvotes: 1

Related Questions