-4

我已经编写了程序,但是我有两个问题,需要帮助来纠正。问题是

1)我不希望计数器 i 从 1 变为 x,因为它会尝试对每个小于实际用户输入的数字进行可分性测试。我需要它从 2 开始 i 一直到 12 以便您只尝试 2-12 的测试。2)整除性测试是正确的,它适用于每个数字,但这不是程序描述中所要求的。我需要为每个可分性测试实现上述算法。(我已经研究过,但不知道该怎么做)

这是我的代码,下面是作业:

import java.io.PrintStream;
import java.util.Scanner;

public class rwsFinalExam
{
    public static void main(String [] args)
    {
        Scanner scanner = new Scanner( System.in ); //allows input from concole
        PrintStream out = System.out;               //assigning System.out to PrintStream

        out.print( "Input a valid whole number: " ); //ouput directions for end user to enter a whole number

        String input = scanner.next();  //holds end user input
        int number;                     //data type and variable 

        try 
        {
            number = Integer.parseInt(input);   //assinging value to number //integer.parseInt method converts string to int
        }
        catch (Exception e)
        {
            out.println(input + " is not a valid number");
            return;
        }

        if (number < 0)
        {
            out.println(number + " is not a valid number");
            return;
        }

        printDivisors(number);
    }

    private static void printDivisors(int x)
    {
        PrintStream out = System.out;
        for (int i=1; i<x; i++) 
        {
            if (isDivisibleBy(x, i)) //checking divisibility 
            {
                out.println(x + " is divisible by " + i); //output when value is divisible 
            }
            else
            {
                out.println(x + " is not divisible by " + i); //output when value not divisible
            }//end if else
        }//end for
    }//end private static

    private static Boolean isDivisibleBy(int x, int divisor)
    {
        while (x > 0)
        {
            x -= divisor;
            if (x == 0)
            {
                return true;
            }
        }
        return false;
    }//end
}//end class rwsFinalExam

我需要我的输出看起来像这样.. 不能使用 % 模数运算符

输入一个有效的整数:ABC

输出:ABC 不是有效数字 按任意键继续。. .

输入一个有效的整数:-1

输出:-1 is not a valid number 按任意键继续。. .

输入一个有效的整数:15

输出:15 不能被 2 整除。15 不能被 3 整除。15 不能被 4 整除。15 不能被 5 整除。15 不能被 6 整除。15 不能被 7 整除。15 不能被 8 整除。15不能被 9 整除。15 不能被 10 整除。15 不能被 11 整除。15 不能被 12 整除。按任意键继续。. .

4

1 回答 1

2

要测试是否可以在不使用的情况下a整除,您可以执行以下操作:ba % b

boolean divisible = (a / b * b == a);

这样做的原因a / b是整数(即截断)除法。

于 2012-12-09T22:19:42.443 回答