从main方法调用,当值超过给定数量时,如何使用while或for循环计数?

时间:2017-06-10 06:09:38

标签: java

当我尝试在这个问题中使用子模块时遇到同样的问题。你能帮我吗?

  

问题陈述如下:    如果他的体重增加到乘客总重量超过承载能力,则不应计算最后一名乘客。

感谢。

import java.util.*;
public class Exam2

    {   
        public static void main(String []args)
        {
            int inputmax ;
            int inputweight =0;
            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(thesum,inputweight,inputmax,count));
        } 
        public static int count(int thesum,int inputweight,int inputmax,int count)
        {
            while(inputweight !=0)
            {
                if(thesum+inputweight >= inputmax)
                {
                    break;
                }    
            }
            return count;
        }
        }

1 个答案:

答案 0 :(得分:0)

main中的while循环进行以下更改:

 thesum += inputweight;
 if(thesum>inputmax)
    break;
 count++;

您不需要具有显式计数功能。