请你编写一个方法(函数),功能要求从参数x累加到y,并返回累加后的整数结果。

public class TestFor
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        
        try
        {
            System.out.println("请输入x的值:");
            
            int x = scanner.nextInt();
            
            System.out.println("请输入y的值:");
            
            int y = scanner.nextInt();
            
            int result = calcutateTest(x, y);
            
            System.out.println("输出的结果为:" + result);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    
    private static int calcutateTest(int x,int y)
    {
        int result = 0;
        
        while(x <= y)
        {
            result += x;   //  result = result + x;
            
            x++;   //  x 自增
        }
        
        return result;   //
    }
}

面试官要求累加,并且要求面试者手写编程,这题看似简单,却不简单,假如你只用六七行代码就实现了,那么面试官就不会考虑你了!你可以多写几种方法去实现!

原文地址:https://www.cnblogs.com/javacatalina/p/6653151.html