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方法在我的代碼:基本的java程序設計方法
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");
}
但你已經建立了一個總和? – Fildor
我該如何取得這一結果,並使其自己的方法稱爲findSum以下processInput – basicjava
shouldProcess不包括在內。你說的少於12而不是<= 12 – Beto