i have the program written however I have two problems and need assistance to correct. the problems are
1) i do not want the counter i to go from 1 to x because then it would try the divisibility test for every number less than the actual user input. I need it to start i from 2 and go until 12 so that you try the test for 2-12 only.
2) The divisibility test is correct and it works for every number but thats not whats asked in the program description. I need to implement the mentioned algorithms for each divisibility test. (which i have researched but am not sure how to do it)
here is my code and below is the assignment:
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
{
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
i need my output to look like this.. cannot use % modulus operator
Input a valid whole number: ABC
Otuput: ABC is not a valid number Press any key to continue . . .
Input a valid whole number: -1
Output: -1 is not a valid number Press any key to continue . . .
Input a valid whole number: 15
Output: 15 is not divisible by 2. 15 is divisible by 3. 15 is not divisible by 4. 15 is divisible by 5. 15 is not divisible by 6. 15 is not divisible by 7. 15 is not divisible by 8. 15 is not divisible by 9. 15 is not divisible by 10. 15 is not divisible by 11. 15 is not divisible by 12. Press any key to continue . . .
解决方案
To test whether a is divisible by b without using a % b, you could do the following:
boolean divisible = (a / b * b == a);
The reason this works that that a / b is the integer (that is, truncating) division.