java程序 - 带变换的可分性测试 - 我如何在textpad中写这个

时间:2012-12-09 22:17:57

标签: java math computer-science division integer-division

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

1)我不希望计数器i从1变为x,因为它会尝试对每个小于实际用户输入的数字进行可分性测试。我需要它从2开始我直到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

Otuput:ABC不是有效数字按任意键继续。 。

输入有效的整数:-1

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

输入有效的整数:15

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

1 个答案:

答案 0 :(得分:2)

要测试a是否可以b整除而不使用a % b,您可以执行以下操作:

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

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