用方法进行基本的java编程

时间:2016-06-28 13:23:58

标签: java

import java.util.Scanner;
public class hey {



public static void main( String[] args )
{
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter an integer between 6 and 12, inclusive: ");
    int num = in.nextInt();
    System.out.print(num);
    System.out.println();
    boolean result = shouldProcess(num);
    processInput(result, num); // passing the result and num

}

public static boolean shouldProcess(int n) 
{
    if (n>=6 && n<12)
    {
        return true;
    }
    else
    {
        return false;
    } 
}

public static void processInput(boolean result2, int num) // added int num argument
{
    if (result2 == true)
    {

            int sum = 0; 
            for (int i = 1; i <=num; i++)
            {
                  sum +=i;
            }
            System.out.println("The sum from 1 to " + num+ " is: " +sum); 

    }
    else 
    {
        System.out.println("Number is outside of acceptable range");
    }
}  
}

此代码在shouldProcess中返回一个布尔值,如果给定的数字介于6和12之间(包括),则返回true,否则返回false。然后我创建了方法processInput,它使用shouldProcess来确定它是否可以计算并输出总和(仅当方法shouldProcess返回true时。查找总和的方法称为findSum。所以我不太清楚如何采取以下方法阻止并在我的代码中创建这个findSum方法:

public static void processInput(boolean result2, int num) 
{
    if (result2 == true)
    {

            int sum = 0; 
            for (int i = 1; i <=num; i++)
            {
                  sum +=i;
            }
            System.out.println("The sum from 1 to " + num+ " is: " +sum); 

    }
    else 
    {
        System.out.println("Number is outside of acceptable range");
    }

1 个答案:

答案 0 :(得分:0)

if (result2 == true)
{

        int sum = 0; 
        for (int i = 1; i <=num; i++)
        {
              sum +=i;
        }
        System.out.println("The sum from 1 to " + num+ " is: " +sum); 

}

将是:

if (result2 == true)
{

        System.out.println("The sum from 1 to " + num+ " is: " +findSum(num)); 

}

public static int findSum(num){
     int sum = 0;
     for( int i = 1; i <= num; i++ ){ sum+= i; } // usually I'll use int i = 0 and add an offset in the loop.
     return sum;
}

顺便说一下:你可以缩短你的shouldProcess:

public static boolean shouldProcess(int n) 
{
    return (n>=6 && n<=12); // both inclusive!
}