-4

プログラムを作成しましたが、2 つの問題があり、修正するための支援が必要です。問題は

1) カウンター i を 1 から x に変更したくありません。これは、実際のユーザー入力よりも小さい数値ごとに割り切れるテストを試行するためです。2 から 12 まで i を開始して、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 は 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 に答える