Programmers who exhibited self-regulated programming techniques paused to consider alternate approaches, revisit requirements, or think about which programming concepts to use. Additionally, we found patterns in burst sizes for different types of exercises.
Consider the class:
public class Employee {
int role;
float salary;
}
Write code to
- Create a method
verifyEmployee
that takes parametersEmployee e1
andEmployee e2
- Write a statement that returns a
-1
if e1’s role is less than e2’s and e1’s salary is also less than e2’s. - Write another statement that returns
0
ife1
ande2
have the same roles and salaries. - Write another statement that returns a
1
if e1’s role is greater than e2’s and e1’s salary is also greater than e2’s. - Write a final line that returns a
2
if none of the previous rules could be verified.
Write your code below.
The following method returns 0
if x
is not divisible by n
and 1
if x
is divisible by n
.
public static int xIsDivisibleByN(int x, int n) {
if (x % n == 0) {
return 1;
} else {
return 0;
}
}
Create a program that asks the user to input a number and uses the method xIsDivisibleByN
to determine if it is prime, that is, if it is divisible by no number except itself and 1
. Assume that the user will input an integer greater than or equal to 2
.
Follow the steps below to create your code:
- Write a statement to import
java.util.Scanner
- Declare a public class "Main".
Within the
Main
class, do the following: - Declare a public static method
main
which does not return anything and takes as a parameter an array of Strings namedargs
.
Within the main method, do the following:
- Declare an integer variable named
a
. - Define a new Scanner object
sc
which takesSystem.in
as a parameter. - Set a to the returned value of Scanner sc's
nextInt()
method. - Declare an integer
isPrime
and set it to1
. - Declare an integer variable
root
and set it to the square root of a casted as an integer. - Create a for loop that uses integer variable n to go from
2
toroot
(inclusive), incrementally increasing by1
. Inside that for loop, do the following: - Set
isPrime
to the value returned by passinga
andn
into thexIsDivisibleByN
method. - If
isPrime
to0
, break out of the for loop.
Outside of the for loop, do the following:
- If
isPrime
is equal to1
, print the formatted string "Number {num} is prime" (where {num} the value stored in a) - If the if statement is not true, print the formatted string "Number {num} is NOT prime" (where {num} the value stored in a)