Submit Chapter4.java with four public static methods for the solutions of Exerci
ID: 3758448 • Letter: S
Question
Submit Chapter4.java with four public static methods for the solutions of Exercises starting on page 305 of building java programs:
#2 repl (name here is repl as in replicate, 2 points always just on spellling)
Write a method called rep1 that accepts a String and a number of repetitions as parameters and returns the String concatenated that many times. For example, the call rep1("hello", 3) should return "hellohellohello". If the number of repetitions is zero or less, the method should return a empty string.
#5 pow (Use of Math Class not allowed for this one)
Write a method called pow that accepts a base and an exponent as parameters and return the base raised to the given power. For example, the call pow(3, 4) should return 3 * 3 * 3 *3 *3, or 81. Assume that the base and exponent are nonnegative.
#15 getGrade (I require some calculations here, an if-else block, or switch, with no more than 5 cases, interpolate between points)
#21B A "perfect number" is a positive integer that is the sum of all its proper factors. The first two perfect numbers are 6 and 28, since 1+2+3=6 and 1+2+4+7+14=28. Write a public static method perfectNumber that takes one integer as a parameter, and returns a boolean, true if the passed parameter is a perfect number, false otherwise. A call to perfectNumber(6); should return true, while perfectNumber(999999); returns false
Explanation / Answer
public static String repl(String baseString, int num)
{
String finalString = "";
for(int i = 1; i <= num; i++)
finalString += baseString;
return finalString;
}
public static int pow(int base, int power)
{
int result = 1;
for(int i = 1; i <= power; i++)
result *= base;
return result;
}
public static double getGrade(int score)
{
if(score < 60)
return 0.0;
else if(score >= 60 && score <= 62)
return 0.7;
else if(score > 62 && score < 95)
return 0.7 + ((score-62)*0.1);
else
return 4.0;
}
public static boolean perfectNumber(int num)
{
int sum = 0;
for(int j = 2; j<= (int)Math.sqrt(num); j++) //Loop for checking the factors.
if(num % j == 0) //If the remainder is 0.
{
sum += j; //Add that number to sum.
sum += num / j; //Also add the other multiple with which is multiplies.
}
sum++;
if(sum == num) //If the sum of all the factors is equal to the number.
return true;
else
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.