感谢。
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);
}
}
答案 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++;
}
`