2017-06-10 28 views
0

這是我的工作 我有一個問題,就是如果最後一位乘客的體重增加到總乘客重量超過承載能力,就不應該算在內。當值超過給定的數字時,我如何使用while或for循環進行計數?

謝謝。

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

目前什麼是錯呢? –

+0

你必須檢查結果是否會在添加之前超過容量:'if(thesum + inputweight> = inputmax){break; } else {thesum + = inputweight;計數++; }' –

回答

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

`

+0

嘿我的也是正確的:) –

相關問題