In: Computer Science
Create JAVA PROGRAM, and write comment for codes also.
4) Prompt the user for how much stuff a truck can carry, in pounds. Then ask them for the weight of each thing they add until they stop. Don't forget to be safe.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
// taking user input of capacity of truck and declaring
variables
Scanner sc = new Scanner(System.in);
System.out.print("Enter how much stuff a truck can carry(in
pounds): ");
int total = 0, curr, capacity = sc.nextInt();
while(true) // looping for infinite times
{
// taking the weight of a product
System.out.print("Enter weight of a product(-1 to stop): ");
curr = sc.nextInt();
if(total + curr > capacity ) // stopping user to enter
{
System.out.print("This thing can't fit in truck.");
break;
}
total += curr;
if(total== capacity) // exactly filled case
{
System.out.print("Truck is filled.");
break;
}
}
// printing the filled amount
System.out.println("\nTruck has products of weight " + total
);
}
}
/*OUTPUT
Enter how much stuff a truck can carry(in pounds): 100
Enter weight of a product(-1 to stop): 10
Enter weight of a product(-1 to stop): 20
Enter weight of a product(-1 to stop): 30
Enter weight of a product(-1 to stop): 25
Enter weight of a product(-1 to stop): 10
Enter weight of a product(-1 to stop): 20
This thing can't fit in truck.
Truck has products of weight 95
Enter how much stuff a truck can carry(in pounds): 100
Enter weight of a product(-1 to stop): 50
Enter weight of a product(-1 to stop): 50
Truck is filled.
Truck has products of weight 100
*/
// Hit the thumbs up if you are fine with the answer. Happy Learning!