使用方法

时间:2017-11-05 19:32:14

标签: java

答案可能是盯着我的脸,但我一直在看这个词,这些话语在一起模糊。赋值是让用户输入3个数字,使用方法将数字加在一起,然后使用不同的方法确定总和是否为素数。

package chpt6_Project;
import java.util.Scanner;


public class Chpt6_Project {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int num1;
        int num2;
        int num3;   

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the first number: ");
        num1 = scan.nextInt();

        System.out.println("Enter the second number: ");
        num2 = scan.nextInt();

        System.out.println("Enter the third number: ");
        num3 = scan.nextInt();

        Chpt6_Project.sum(num1, num2, num3);

        if(isPrime()) {
            System.out.println("The number is prime");
        } else {
            System.out.println("The number is not prime.");
        }
    }

    public static void sum(int num1, int num2, int num3) {
        int total = num1 + num2 + num3;
        System.out.println(total);
    }

    public static boolean isPrime(int total) {
        if((total > 2 && total % 2 == 0) || total == 1) {
            return false;
        }

        for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
            if (total % i == 0) {
                return false;
            }
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:3)

编辑代码如下,你应该做的。

sum函数现在返回计算的总和,此值由main传递给isPrime函数,该函数将返回正确的值

package chpt6_Project;
import java.util.Scanner;


public class Chpt6_Project {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int num1;
    int num2;
    int num3;


    Scanner scan = new Scanner(System.in);

    System.out.println("Enter the first number: ");
    num1 = scan.nextInt();

    System.out.println("Enter the second number: ");
    num2 = scan.nextInt();

    System.out.println("Enter the third number: ");
    num3 = scan.nextInt();



    if(isPrime(Chpt6_Project.sum(num1, num2, num3))) {
        System.out.println("The number is prime");
    } else {
        System.out.println("The number is not prime.");
    }

}

public static int sum(int num1, int num2, int num3) {
    int total = num1 + num2 + num3;
    System.out.println(total);
    return total;
}


public static boolean isPrime(int total) {

    if((total > 2 && total % 2 == 0) || total == 1) {
        return false;
    }

    for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {

        if (total % i == 0) {
            return false;
        }
    }
    return true;
}

Morover我想这是一个功课,但还有更好的方法。例如,不需要求和函数。