MyprogrammingLab 5.2, Java Chapter 5, Java Chapter 5, MyProgrammingLab 5 Methods, MPL
11) When an argument is passed to a method: A) its value is copied into the method's parameter variable B) its value may be changed within the called method C) values may not be passed to methods D) the method must not assign another value to the parameter that receives the argument
Answer: A
15) When an object, such as a String, is passed as an argument, it is: A) actually a reference to the object that is passed B) passed by value like any other parameter value C) encrypted D) necessary to know exactly how long the string is when writing the program
Answer: A
18) When you pass an argument to a method, be sure that the argument's data type is compatible with: A) the parameter variable's data type B) the method's return type C) the version of Java currently being used D) IEEE standards
Answer: A
19) A parameter variable's scope is: A) the method in which the parameter is declared B) the class to which the method belongs C) the main method D) All of the above
Answer: A
24) What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; } A) 18.0 B) 18 (as an integer) C) 8 D) This is an error.
Answer: A
3) This type of method performs a task and sends a value back to the code that called it. A) value-returning B) void C) complex D) local
Answer: A
31) In the following code, Integer.parseInt(str), is an example of: int num; string str = "555"; num = Integer.parseInt(str) + 5; A) a value-returning method B) a void method C) a local variable D) a complex method
Answer: A
34) You should always document a method by writing comments that appear: A) just before the method's definition B) just after the method's definition C) at the end of the file D) only if the method is more than five lines long
Answer: A
36) If you attempt to use a local variable before it has been given a value: A) a compiler error will occur B) the local variable will always contain the value 0 C) the results will be unpredictable D) the local variable will be ignored
Answer: A
41) Values stored in local variables: A) are lost between calls to the method in which they are declared B) retain their values from the last call to the method in which they are declared C) may be referenced by the calling method D) may be referenced by any other method, if the method in which they are declared is a public method
Answer: A
46) The process of breaking a problem down into smaller pieces is sometimes called: A) divide and conquer B) scientific method C) top-down programming D) whole-into-part
Answer: A
6) In the header, the method name is always followed by this: A) parentheses B) return type C) data type D) braces
Answer: A
1) Methods are commonly used to: A) speed up the compilation of a program B) break a problem down into small manageable pieces C) emphasize certain parts of the logic D) document the program
Answer: B
10) Values that are sent into a method are called: A) variables B) arguments C) literals D) types
Answer: B
16) All @param tags in a method's documentation comment must: A) end with a */ B) appear after the general description of the method C) appear before the method header D) span several lines
Answer: B
17) A special variable that holds a value being passed into a method is called what? A) Modifier B) Parameter C) Alias D) Argument
Answer: B
25) In a @return tag statement the description: A) cannot be longer than one line B) describes the return value C) must be longer than one line D) describes the parameter values
Answer: B
26) When a method tests an argument and returns a true or false value, it should return: A) a zero for true and a one for false B) a boolean value C) a zero for false and a non-zero for true D) a method should not be used for this type test
Answer: B
30) This type of method performs a task and then terminates. A) value-returning B) void C) local D) simple
Answer: B
35) When an argument value is passed to a method, the receiving parameter variable is: A) declared within the body of the method B) declared in the method header inside the parentheses C) declared in the calling method D) uses the declaration of the argument
Answer: B
4) In the following code, System.out.println(num) is an example of: double num = 5.4; System.out.println(num); num = 0.0; A) a value-returning method B) a void method C) a complex method D) a local variable
Answer: B
48) Assume that the following method header is for a method in class A. public void displayValue(int value) Assume that the following code segments appear in another method, also in class A. Which contains a legal call to the displayValue method? A) int x = 7; void displayValue(x); B) int x = 7; displayValue(x); C) int x = 7; displayValue(int x); D) int x = 7; displayValue(x)
Answer: B
8) Which of the following is NOT part of a method call? A) method name B) return type C) parentheses D) all of the above are part of a method call
Answer: B
12) What is wrong with the following method call? displayValue (double x); A) There is nothing wrong with the statement. B) displayValue will not accept a parameter. C) Do not include the data type in the method call. D) x should be a String.
Answer: C
13) Given the following method header, which of the method calls would be an error? public void displayValues(int x, int y) A) displayValue(a,b); // where a is a short and b is a byte B) displayValue(a,b); // where a is an int and b is a byte C) displayValue(a,b); // where a is a short and b is a long D) They would all give an error.
Answer: C
14) Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } A) showProduct(5.5, 4.0); B) showProduct(10.0, 4); C) showProduct(10, 4.5); D) showProduct(33.0, 55.0);
Answer: C
23) The header of a value-returning method must specify this. A) The method's local variable names B) The name of the variable in the calling program that will receive the returned value C) The data type of the return value D) All of the above
Answer: C
27) The phrase divide and conquer is sometimes used to describe: A) the backbone of the scientific method B) the process of dividing functions C) the process of breaking a problem down into smaller pieces D) the process of using division to solve a mathematical problem
Answer: C
33) Which of the following is included in a method call? A) return type B) method modifiers C) parentheses D) return variable
Answer: C
37) What will be the result of the following code? int num; string str = "555"; num = Integer.parseInt(string str) + 5; A) num will be set to 560. B) str will have a value of "560". C) The last line of code will cause an error. D) Neither num or str will be changed.
Answer: C
38) Given the following method header, which of the method calls would be an error? public void displayValues(double x, int y) A) displayValue(a,b); // where a is a long and b is a byte B) displayValue(a,b); // where a is an int and b is a byte C) displayValue(a,b); // where a is a short and b is a long D) They would all give an error.
Answer: C
40) When writing the documentation comments for a method, you can provide a description of each parameter by using a: A) @comment tag B) @doc tag C) @param tag D) @return tag
Answer: C
45) To document the return value of a method, use this in a documentation comment. A) The @param tag B) The @comment tag C) The @return tag D) The @returnValue tag
Answer: C
47) Any method that calls a method with a throws clause in its header must: A) handle the potential exception B) have the same throws clause C) both of the above D) do nothing, the called program will take care of the throws clause
Answer: C
7) This part of a method is a collection of statements that are performed when the method is executed. A) method header B) return type C) method body D) method modifier
Answer: C
9) If method A calls method B, and method B calls method C, and method C calls method D, when method D finishes, what happens? A) Control is returned to method A. B) Control is returned to method B. C) Control is returned to method C. D) The program terminates.
Answer: C
2) Which of the following is NOT a benefit derived from using methods in programming? A) Pproblems are more easily solved. B) simplifies programs C) code reuse D) All of the above are benefits.
Answer: D
20) The lifetime of a method's local variable is: A) the duration of the program B) the duration of the class to which the method belongs C) the duration of the method that called the local variable's method D) only while the method is executing
Answer: D
21) Local variables: A) are hidden from other methods B) may have the same name as local variables in other methods C) lose the values stored in them between calls to the method in which the variable is declared D) All of the above
Answer: D
28) In a general sense, a method is: A) a plan B) a statement inside a loop C) a comment D) a collection of statements that performs a specific task
Answer: D
29) Breaking a program down into small manageable methods: A) makes problems more easily solved B) allows for code reuse C) simplifies programs D) all of the above
Answer: D
32) Which of the following is NOT a part of the method header? A) return type B) method name C) parentheses D) semicolon
Answer: D
39) Which of the following would be a valid method call for the following method? public static void showProduct(double num1, int num2) { double product; product = num1 * num2; System.out.println("The product is " + product); } A) showProduct("5", "40"); B) showProduct(10.0, 4.6); C) showProduct(10, 4.5); D) showProduct(3.3, 55);
Answer: D
42) Local variables can be initialized with: A) constants B) parameter values C) the results of an arithmetic operation D) any of the above
Answer: D
43) A value-returning method must specify this as its return type in the method header. A) an int B) a double C) a boolean D) any valid data type
Answer: D
44) What will be returned from the following method? public static int methodA() { double a = 8.5 + 9.5; return a; } A) 18.0 B) 18 (as an integer) C) 8.0 D) This is an error.
Answer: D
5) To create a method you must write its: A) header B) return type C) body D) definition
Answer: D
22) Which of the following values can be passed to a method that has an int parameter variable? A) float B) double C) long D) All of the above E) None of the above
Answer: E
T/F: In the method header the static method modifier means the method is available to code outside the class.
Answer: FALSE
T/F: In the method header, the method modifier public means that the method belongs to the class, not a specific object.
Answer: FALSE
T/F: Only constants and variables may be passed as arguments to methods.
Answer: FALSE
10) No statement outside the method in which a parameter variable is declared can access the parameter by its name.
Answer: TRUE
T/F: A parameter variable's scope is the method in which the parameter is declared.
Answer: TRUE
T/F: A value-returning method can return a reference to a non-primitive type.
Answer: TRUE
T/F: Any method that calls a method with a throws clause in its header must either handle the potential exception or have the same throws clause.
Answer: TRUE
T/F: Constants, variables, and the values of expressions may be passed as arguments to a method.
Answer: TRUE
T/F: Methods are commonly used to break a problem into small manageable pieces.
Answer: TRUE
T/F: The expression in a return statement can be any expression that has a value.
Answer: TRUE
T/F: Two general categories of methods are void methods and value returning methods.
Answer: TRUE
T/F: You must have a return statement in a value-returning method.
Answer: TRUE
Assume that x is a variable that has been declared as a double and been given a value . Write an expression to compute the quartic root of x. The quartic root of a number is the square root of its square root. EXAMPLES: For example, the quartic root of 16.0 is 2.0 because: the square root of 16.0 is 4.0 and the square root of 4.0 is 2.0. Another example: the quartic root of 81.0 is 3.0 because the square root of 81.0 is 9.0 and the square root of 9.0 is 3.0. Thus, to find the quartic root of a number you take the square root of the number and then take the square root of that. In this exercise you must find the quartic root of x in a single expression -- you must not write any statements . Also, you may only use the sqrt() static method defined in the Math class -- no other methods . (HINT: you will need to call the Math.sqrt() method twice-- and you will need to pass the return value of one of those calls as argument to the other call. AND REMEMBER: write an expression , not a statement .)
Math.sqrt(Math.sqrt(x))
Write a method min that has three string parameters and returns the smallest.
String min(String a, String b, String c) { String min1 = a; if (b.compareTo(min1) < 0) min1 = b; if (c.compareTo(min1) < 0) min1 = c; return min1; }
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of strings and two int variables, count and longest, write the code necessary to examine all the strings in the input source and determine how long the longest string (or strings are). That value should be assigned to longest; the number of strings that are of that length should be assigned to count.
count = 0; longest =0; String myString = new String(); while (input.hasNext()){ myString = input.next(); if (myString.length() == longest) count++; else if (myString.length() > longest){ longest = myString.length(); count = 1; } }
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of lines of text and an int variable named count, write the code necessary to count the lines of text in the input source and place that value into count.
count = 0; while(input.hasNext()){ input.nextLine(); count++; }
toThePowerOf is a method that accepts two int arguments and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume, has already been declared. Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3 and that stores this value in cubeVolume. Assume that toThePowerOf is defined in the same class that calls it.
cubeVolume = toThePowerOf ( cubeSide , 3 ) ;
toThePowerOf is a method that accepts two int arguments and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized . Another int variable , cubeVolume, has already been declared . Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3 and that stores this value in cubeVolume. Assume that toThePowerOf is defined in the same class that calls it.
cubeVolume = toThePowerOf(cubeSide, 3);
Given an int variable n that has already been declared, write some code that repeatedly reads a value into n until at last a number between 1 and 10 (inclusive) has been entered. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
do { n = stdin.nextInt(); } while (n > 10 || n < 1);
Given a String variable response that has already been declared, write some code that repeatedly reads a value from standard input into response until at last a Y or y or N or n has been entered. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
do { response = stdin.next(); } while (!response.equals("Y") && !response.equals("y") && !response.equals("N") && !response.equals("n"));
add is a method that accepts two int arguments and returns their sum. Two int variables, euroSales and asiaSales, have already been declared and initialized. Another int variable, eurasiaSales, has already been declared. Write a statement that calls add to compute the sum of euroSales and asiaSales and that stores this value in eurasiaSales. Assume that add is defined in the same class that calls it.
eurasiaSales = add ( euroSales, asiaSales);
add is a method that accepts two int arguments and returns their sum . Two int variables , euroSales and asiaSales, have already been declared and initialized . Another int variable , eurasiaSales, has already been declared . Write a statement that calls add to compute the sum of euroSales and asiaSales and that stores this value in eurasiaSales. Assume that add is defined in the same class that calls it.
eurasiaSales = add(euroSales, asiaSales);
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of lines, write the code necessary to read in every line and print them all out on a single line, separated by a space. There should NOT be a trailing space at the end of the line.
if (input.hasNext()) System.out.print(input.nextLine()); while (input.hasNext()){ System.out.print(" " + input.nextLine()); }
Given that a method receives three parameters a, b, c, of type double, write some code, to be included as part of the method, that determines whether the value of "b squared" - 4ac is negative. If negative, the code prints out the message "no real solutions" and returns from the method
if((Math.pow(b,2) - 4 * a * c) < 0) { System.out.print("no real solutions"); }
Given that a method receives three parameters a, b, c, of type double, write some code, to be included as part of the method, that checks to see if the value of a is 0; if it is, the code prints the message "no solution for a=0" and returns from the method.
if(a == 0) { System.out.print("no solution for a=0"); }
Given that a method receives three parameters a, b, c, of type double, write some code, to be included as part of the method, that determines whether the value of "b squared" - 4ac is negative. If negative, the code prints out the message "no real solutions" and returns from the method Instructor Notes: Solution: if (b*b - 4.0*a*c < 0.0) { System.out.println("no real solutions"); return; }
if(b*b - 4.0 *a*c < 0) { System.out.println("no real solutions"); return; }
Given the integer variables x, y, and z, write a fragment of code that assigns the smallest of x, y, and z to another integer variable min. Assume that all the variables have already been declared and that x, y, and z have been assigned values.
if(x < y){ if(x<z){ min = x; }else{ min = z; } }else{ if(y<z){ min = y; }else{ min = z; } }
. Test Average and GradeWrite a program that asks the user to enter five test scores. The program should display aletter grade for each score and the average test score. Write the following methods in theprogram:calcAverage:This method should accept five test scores as arguments and return theaverage of the scores.determineGrade:This method should accept a test score as an argument and return aletter grade for the score, based on the following grading scale:Score Letter Grade90-100 A80-89 B70-79 C60-69 DBelow 60 F
import java.util.Scanner; public class TestAvgAndGrade { public static void main(String[] args) { Scanner kb = new Scanner(System.in); char letterGrade = 'A'; System.out.print("Enter test grade for student 1:"); double score1 = kb.nextDouble(); System.out.print(" Enter test grade for student 2:"); double score2 = kb.nextDouble(); System.out.print(" Enter test grade for student 3:"); double score3 = kb.nextDouble(); System.out.print(" Enter test grade for student 4:"); double score4 = kb.nextDouble(); System.out.print(" Enter test grade for student 5:"); double score5 = kb.nextDouble(); System.out.print(" The letter grades are as follows:\n"); System.out.println("Student 1: "+ determineGrade(score1)); System.out.println("Student 2: "+ determineGrade(score2)); System.out.println("Student 3: "+ determineGrade(score3)); System.out.println("Student 4: "+ determineGrade(score4)); System.out.println("Student 5: "+ determineGrade(score5)); double average = calcAverage(score1,score2,score3,score4,score5); System.out.printf("The average grade was: %.2f\n",average); } public static char determineGrade(double score){ char grade; if(score <60) grade = 'F'; else if(score <70) grade = 'D'; else if(score <80) grade ='C'; else if(score <90) grade = 'B'; else grade ='A'; return grade; } public static double calcAverage(double sc1,double sc2,double sc3, double sc4,double sc5){ double av = (double)(sc1+sc2+sc3+sc4+sc5)/5; return av; } }
Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a CONSECUTIVE DUPLICATE. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6. Note that the last 3 is not a consecutive duplicate because it was preceded by a 7. Write some code that uses a loop to read such a sequence of non-negative integers, terminated by a negative number. When the code finishes executing, the number of consecutive duplicates encountered is printed. In this case,3 would be printed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int firstNumber, secondNumber = -1, cDuplicate = 0; firstNumber = stdin.nextInt(); while (stdin.hasNextInt() && firstNumber >= 0) { if (firstNumber == secondNumber) { cDuplicate++; } else secondNumber = firstNumber; firstNumber = stdin.nextInt(); } System.out.println(cDuplicate);
Write a loop that reads strings from standard input where the string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters) is read in. Other strings are ignored. After the loop, your code should print out 3 lines: the first consisting of the string "land:" followed by the number of "land" strings read in, the second consisting of the string "air:" followed by the number of "air" strings read in, and the third consisting of the string "water:" followed by the number of "water" strings read in. Each of these should be printed on a separate line. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int land = 0; int air = 0; int water = 0; String str = new String(); while(!(str.equals("xxxxx"))) { str = stdin.next(); if(str.equals("land")) land++; else if(str.equals("air")) air++; else if(str.equals("water")) water++; } System.out.println("land:" + land); System.out.println("air:" + air); System.out.println("water:" + water);
Write the definition of a method min that has two int parameters and returns the smaller.
int min(int num1, int num2) { if(num1 < num2) return num1; else return num2; }
Write a loop that reads positive integers from standard input, printing out those values that are even, each followed by a space, and that terminates when it reads an integer that is not positive. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int num=1; while (num>0){ num = stdin.nextInt(); if ((num % 2) == 0 && num > 0 ){ System.out.print(num + " "); } }
Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, each followed by a space, and that terminates when it reads an integer that is not positive. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int number = 0; while (stdin.hasNextInt() && number >= 0){ number =stdin.nextInt(); if (number > 100) System.out.print(number + " "); }
Assume the input data is structured as follows: first there is a non-negative integer specifying the number of employee timesheets to be read in. This is followed by data for each of the employees. The first number for each employee is an integer that specifies their pay per hour in cents. Following this are 5 integers, the number of hours they worked on each of the days of the workweek. Given this data, and given that an int variable total has been declared, write a loop and any necessary code that reads the data and stores the total payroll of all employees in total. Note that you will have to add up the numbers worked by each employee and multiply that by that particular employee's pay rate to get the employee's pay for the week-- and sum those values into total. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int numberOfTimesheets; int centsPerHour = 0; int hoursWorked; total = 0; numberOfTimesheets = stdin.nextInt(); for(int i = 1; i <= numberOfTimesheets; i++) { hoursWorked = 0; centsPerHour = stdin.nextInt(); for (int j = 1; j <= 5; j++) { hoursWorked = hoursWorked + stdin.nextInt(); } total = total + (hoursWorked * centsPerHour); }
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, separated by a space and on a single line, the sum of all the even integers read and the sum of all the odd integers read. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int odd=0; int even=0; int i=1; while (i>0){ i = stdin.nextInt(); if ((i % 2)==0 && (i>0)){ even+=i; } if ((i % 2)!=0 && (i>0)){ odd+=i; } } System.out.print(even + " " + odd);
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int odd=0; int even=0; int i=1; while (i>0){ i = stdin.nextInt(); if ((i % 2)==0 && (i>0)){ even+=i; } if ((i % 2)!=0 && (i>0)){ odd+=i; } } System.out.print(even);
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself and separated by spaces, the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by at least one space. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
int odd=0; int oddCount=0; int evenCount=0; int even=0; int i=1; while (i>0){ i = stdin.nextInt(); if ((i % 2)==0 && (i>0)){ even+=i; evenCount++; } if ((i % 2)!=0 && (i>0)){ odd+=i; oddCount++; } } System.out.print(even + " " + odd + " " + evenCount + " " + oddCount);
Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a while loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Use no variables other than n, k, and total and do not modify the value of n.
k = 0 ; total = 0 ; while ( k <= n ) { total = total += k * k * k; k++ ; }
Given an int variable k that has already been declared, use a while loop to print a single line consisting of 88 asterisks. Use no variables other than k.
k=1; while(k<=88) { System.out.print('*'); k++; } System.out.println();
max is a method that accepts two int arguments and returns the value of the larger one. Four int variables, population1, population2, population3, and population4 have already been declared and initialized. Write an expression (not a statement!) whose value is the largest of population1, population2, population3, and population4 by calling max. Assume that max is defined in the same class that calls it.
max(max(population1, population2), max(population3, population4))
max is a method that accepts two int arguments and returns the value of the larger one. Two int variables , population1 and population2, have already been declared and initialized . Write an expression (not a statement !) whose value is the larger of population1 and population2 by calling max. Assume that max is defined in the same class that calls it.
max(population1, population2)
max is a method that accepts two int arguments and returns the value of the larger one. Two int variables, population1 and population2, have already been declared and initialized. Write an expression (not a statement!) whose value is the larger of population1 and population2 by calling max. Assume that max is defined in the same class that calls it.
max(population1,population2)
Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". Let's define a SINGLETON to be a data element that is not repeated immediately before or after itself in the sequence. So, here there are four SINGLETONs (the first appearance of "fish", the first appearance of "bird", "mammal", and the second appearance of "fish"). Write some code that uses a loop to read a sequence of words, terminated by the "xxxxx". The code assigns to the variable n the number of SINGLETONs that were read. (For example in the above data sequence it would assign 4 to n. Assume that n has already been declared. but not initialized. Assume that there will be at least one word before the terminating "xxxxx". ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.
n = 0; String word1, word2, word3; word3 = stdin.next(); word2 = stdin.next(); word1 = stdin.next(); if (!(word3.equals(word2))) n++; if (!(word2.equals(word3)) && (!(word2.equals(word1)))) n++; while (!(word1.equals("xxxxx")) && (stdin.hasNext())) { word3 = word2; word2 = word1; word1 = stdin.next(); if (!(word2.equals(word3)) && (!(word2.equals(word1)))) n++; }
Assume that x is a variable that has been declared as an int and been given a value. Assume that oneMore is a function that receives a single integer parameter and returns a value that is one greater than its argument. (So if you pass 7 to oneMore it will return 8. Thus, the expression oneMore(9) has the value 10. Write an expression whose value is four more than x without using the standard Java arithmetic operators (*,+, etc.). Instead, use calls to oneMore to accomplish this. In this exercise you must write this as a single expression-- you must not write any statements. Also, you may only use the oneMore function-- no other functions or operators.
oneMore(oneMore(oneMore(oneMore(x))))
printErrorDescription is a method that accepts one int argument and returns no value. Write a statement that invokes the method printErrorDescription, passing it the value 14. Assume that printErrorDescription is defined in the same class that calls it.
printErrorDescription ( 14 ) ;
printLarger is a method that accepts two int arguments and returns no value. Two int variables, sales1 and sales2, have already been declared and initialized. Write a statement that calls printLarger, passing it sales1 and sales2. Assume that printLarger is defined in the same class that calls it.
printLarger ( sales1 , sales2 );
printStars is a method that accepts a single int argument and returns no value. It prints as many stars as indicated by its argument. Given a variable x of type double that has been given a value, write a statement that invokes printStars passing x as an argument. Assume that printStars is defined in the same class that calls it.
printStars(x);
printTodaysDate is a method that accepts no arguments and returns no value . Write a statement that calls printTodaysDate. Assume that printTodaysDate is defined in the same class that calls it.
printTodaysDate();
printTodaysDate is a method that accepts no arguments and returns no value. Write a statement that calls printTodaysDate. Assume that printTodaysDate is defined in the same class that calls it.
printTodaysDate();
Write a method, getEmailDomain, that is passed a String argument that is an email address and returns the domain name part. So if "[email protected]" is passed, the method returns "salzberg.de". Assume that the argument will always be a correctly formatted email address.
public String getEmailDomain (String aString) { return aString.substring(aString.indexOf("@") + 1, aString.length()); }
Write a method, getEmailUserName, that is passed a String argument that is an email address and returns the user-name part. So if "[email protected]" is passed, the method returns "mozart". Assume that the argument will always be a correctly formatted email address.
public String getEmailUserName (String aString) { return aString.substring(0, aString.indexOf("@")); }
Write a method, getFirstLine, that is passed a String argument and that returns the first line. (Recall that lines are terminated with the "\n" character.) Assume that the argument contains at least one complete, newline-terminated line.
public String getFirstLine (String aString) { return aString.substring(0, aString.indexOf("\n")); }
Write a method, getSecondLine, that is passed a String argument and that returns the second line, without its newline character. (Recall that lines are terminated with the "\n" character.) Assume that the argument contains at least two complete, newline-terminated lines.
public String getSecondLine (String aString) { return aString.substring(aString.indexOf("\n") + 1, aString.indexOf("\n") + 1 + aString.substring(aString.indexOf("\n") + 1, aString.length()).indexOf("\n")); }
Write a method, makeEmailAddress, that is passed two String arguments: the first is a username, like "leadbelly" and the second is a domain name, like "blues.com". The method returns an email address formed from joining these with an "@": "[email protected]".
public String makeEmailAddress (String aString, String bString) { return aString + "@" + bString; }
Write a method, makeSubjectLine, that gets a String argument and returns the same String but with "Subject: " in front of it. So if the argument is "Are you going to the show?" the method returns "Subject: Are you going to the show?".
public String makeSubjectLine(String text) { return "Subject: " + text; }
Write a method , makeSubjectLine, that gets a String argument and returns the same String but with "Subject: " in front of it. So if the argument is "Are you going to the show?" the method returns "Subject: Are you going to the show?".
public String makeSubjectLine(String text) { return "Subject: " + text; }
Write the definition of a method powerTo, which receives two parameters. The first is a double and the second is an int. The method returns a double. If the second parameter is negative, the method returns zero. Otherwise it returns the value of the first parameter raised to the power of the second parameter.
public double powerTo (double adouble, int aint) { if (aint < 0) { return 0.0; } else { return Math.pow(adouble, (double) aint); } }
Write the definition of a method min that has two int parameters and returns the smaller.
public int min (int aint, int bint){ return Math.min(aint, bint); }
Write a method max that has two string parameters and returns the larger of the two.
public static String max(String a, String b) { return a.compareTo(b)>0? a:b; } or public String max (String a, String b) { if (a.compareTo(b) > 0) { return aString; } else { return bString; } }
Write a static method, getBigWords, that gets a single String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) EXAMPLE: So, if the String argument passed to the method was "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada". ANOTHER EXAMPLE: If the String argument passed to the method was "Send the request to [email protected]", getBigWords would return an array of three elements, "request", "support" and "turingscraft".
public static String[] getBigWords(String sentence) { int totalbigWords, currentWordStart, currentWordEnd, pointer; totalbigWords = currentWordStart = currentWordEnd = pointer = 0; while ((pointer != sentence.length() - 1) && (!sentence.isEmpty())) { if(Character.isLetter(sentence.charAt(pointer))) { currentWordStart = pointer; while ((Character.isLetter(sentence.charAt(pointer))) && (pointer < sentence.length() - 1)) { pointer++; } currentWordEnd = pointer; if (currentWordEnd == sentence.length() - 1) currentWordEnd++; if (currentWordEnd == 0) currentWordEnd++; if (currentWordEnd - currentWordStart > 5) { totalbigWords++; currentWordStart = currentWordEnd = pointer; } } else pointer++; } String[] bigWords = new String[totalbigWords]; totalbigWords = currentWordStart = currentWordEnd = pointer = 0; while (pointer < sentence.length() - 1) { if(Character.isLetter(sentence.charAt(pointer))) { currentWordStart = pointer; while ((Character.isLetter(sentence.charAt(pointer))) && (pointer < sentence.length() - 1 )) { pointer++; } currentWordEnd = pointer; if (currentWordEnd == 0) currentWordEnd++; if (currentWordEnd == sentence.length() - 1) currentWordEnd++; if (currentWordEnd - currentWordStart > 5) { bigWords[totalbigWords] = sentence.substring(currentWordStart, currentWordEnd); totalbigWords++; currentWordStart = currentWordEnd = pointer; } } else pointer++; } return bigWords; }
Write a method, isEmailAddress, that is passed a String argument. It returns true or false depending on whether the argument has the form of an email address. In this exercise, assume that an email address has one and only one "@" sign and no spaces, tabs or newline characters.
public static boolean isEmailAddress (String aString) { if (aString.indexOf("@") != -1) { if (aString.indexOf("@") == aString.lastIndexOf("@")) { if (aString.indexOf(" ") == -1) { if (aString.indexOf("\n") == -1) { if (aString.indexOf("\t") == -1) { return true; } } } } } return false; }
Write the definition of a method powerTo, which receives two parameters. The first is a double and the second is an int. The method returns a double. If the second parameter is negative, the method returns zero. Otherwise it returns the value of the first parameter raised to the power of the second parameter.
public static double powerTo(double a, int b){ double c; if (b < 0) c = 0; else c = Math.pow(a,b); return c; }
Write the definition of a method add, which receives two integer parameters and returns their sum .
public static int add(int a, int b) { int c = a + b; return c; }
Write the definition of a method add, which receives two integer parameters and returns their sum.
public static int add(int a, int b) { int c = a + b; return c; }
Write the definition of a method max that has three int parameters and returns the largest.
public static int max(int a, int b, int c){ return Math.max(Math.max(a,b),c); }
Write the definition of a method min that has two int parameters and returns the smaller.
public static int min(int a, int b) { return a<= b? a:b; }
Write the definition of a method twice, which receives an integer parameter and returns an integer that is twice the value of the parameter .
public static int twice(int a) { int b = 2 * a; return b; }
Write the definition of a method twice, which receives an integer parameter and returns an integer that is twice the value of the parameter.
public static int twice(int a) { int b = 2 * a; return b; }
Write the definition of a method dashedLine, with one parameter, an int. If the parameter is negative or zero, the method does nothing. Otherwise it prints a complete line terminated by a newline to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The method returns nothing.
public static void dashedLine(int x){ if (x > 0) { while(x!=0) { System.out.print("-"); x--; } System.out.println(); } }
Write the definition of a method printAttitude, which has an int parameter and returns nothing. The method prints a message to standard output depending on the value of its parameter. If the parameter equals 1, the method prints disagree If the parameter equals 2, the method prints no opinion If the parameter equals 3, the method prints agree In the case of other values, the method does nothing. Each message is printed on a line by itself.
public static void printAttitude ( int x ){ if ( x == 1 ){ System.out.println ( "disagree" ) ; } if ( x == 2 ){ System.out.println ( "no opinion" ) ; } if ( x == 3 ){ System.out.println ( "agree" ) ; } }
Write the definition of a method printDottedLine, which has no parameters and doesn't return anything. The method prints to standard output a single line (terminated by a newline) consisting of five periods.
public static void printDottedLine (){ System.out.println("....."); }
Write the definition of a method printGrade, which has a char parameter and returns nothing. The method prints on a line by itself the message string Grade: followed by the char parameter (printed as a character) to standard output. Don't forget to put a new line character at the end of your line.
public static void printGrade(char x){ System.out.println("Grade: "+x); }
Write the definition of a method printLarger, which has two int parameters and returns nothing. The method prints the larger value of the two parameters to standard output on a single line by itself.
public static void printLarger (int x,int y){ int z = Math.max(x,y); System.out.println(z); }
Write the definition of a method dashedLine, with one parameter, an int. If the parameter is negative or zero, the method does nothing. Otherwise it prints a complete line terminated by a newline to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The method returns nothing.
public void dashedLine (int a){ if (a>0){ int i; for (i=1;i<=a;i=i+1){ System.out.print("-"); } System.out.println(""); } }
Write the code for invoking a method named sendNumber . There is one int argument for this method. Send the number 5 as an argument to this method. Assume that sendNumber is defined in the same class that calls it.
sendNumber(5) ;
Write the code for invoking a method named sendObject. There is one argument for this method which is of type Customer. Assume that there is a reference to an object of type Customer, in a variable called John_Doe. Use this reference as your argument . Assume that sendObject is defined in the same class that calls it.
sendObject(John_Doe);
Write the code for invoking a method named sendObject. There is one argument for this method which is of type Customer. Assume that there is a reference to an object of type Customer, in a variable called John_Doe. Use this reference as your argument. Assume that sendObject is defined in the same class that calls it.
sendObject(John_Doe);
Write the code for invoking a method named sendSignal. There are no arguments for this method. Assume that sendSignal is defined in the same class that calls it.
sendSignal();
Write the code for invoking a method named sendTwo. There are two arguments for this method: a double and an int. Invoke the method with the double value of 15.955 and the int value of 133. Assume that sendTwo is defined in the same class that calls it.
sendTwo(15.955,133) ;
Write the code for invoking a method named sendVariable. There is one int argument for this method. Assume that an int variable called x has already been declared and initialized to some value. Use this variable's value as an argument in your method invocation. Assume that sendVariable is defined in the same class that calls it.
sendVariable(x) ;
Write a statement that increases the value of the int variable total by the value of the int variable amount. That is, add the value of amount to total and assign the result to total.
total += amount;
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of integers and an int variable named total, write the code necessary to add all the integers in the input source and place their sum into total.
total = 0; while(input.hasNextInt()){ total += input.nextInt( ); }
Given int variables k and total that have already been declared, use a while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.
total=0; for (k=1;k<=50; k++) total+=k*k;
Assume that x is a variable that has been declared as an int and been given a value. Assume that twice is a method (in the same class as the caller) that receives a single integer parameter and returns twice its value. (So if you pass 7 to twice it will return 14. Thus the expression twice(7) has the value 14. Write an expression whose value is eight times that of x without using the standard Java arithmetic operators (*,+, etc.). Instead, use calls to twice to accomplish this. In this exercise you must write this as a single expression-- you must not write any statements. Also, you may only use the twice() function-- no other functions or operators.
twice(twice(twice(x)))
Write the definition of a method printAttitude, which has an int parameter and returns nothing. The method prints a message to standard output depending on the value of its parameter . If the parameter equals 1, the method prints disagree If the parameter equals 2, the method prints no opinion If the parameter equals 3, the method prints agree In the case of other values , the method does nothing. Each message is printed on a line by itself.
void printAttitude (int pint){ if (pint == 1){ System.out.println("disagree"); } if (pint == 2){ System.out.println("no opinion"); } if (pint == 3){ System.out.println("agree"); } }
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of lines, write the code necessary to read in every line and print it out on its own line.
while (input.hasNext()){ System.out.println(input.nextLine()); }
Given an int variable n that has already been declared and initialized to a positive value, use a while loop to print a single line consisting of n asterisks. Use no variables other than n.
while(n > 0){ System.out.print("*"); n--; }