【问题标题】:java program - divisibility test with varification - how do i write this in textpad [closed]java程序-带有可变性的可分性测试-我如何在textpad中写这个[关闭]
【发布时间】:2012-12-09 22:17:56
【问题描述】:

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

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 不是有效数字 按任意键继续。 . .

输入一个有效的整数:15

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

【问题讨论】:

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


【解决方案1】:

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

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

之所以有效,是因为 a / b 是整数(即截断)除法。

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 2011-11-07
    • 2022-06-14
    • 1970-01-01
    • 2019-12-03
    • 2014-07-25
    • 2020-08-06
    • 2016-03-19
    相关资源
    最近更新 更多