CPS150 Final Study

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is the output of the following code snippet? int i = 1; while (i < 10) { System.out.print(i + " "); i = i + 2; if (i == 5) { i = 9; } } A. 1 3 9 B. 1 3 5 C. 1 3 5 9 D. 1 3 5 7 9

A. 1 3 9

What is the output of the given code snippet? int[] mynum = new int[5]; for (int i = 1; i < 5; i++) { mynum[i] = i + 1; System.out.print(mynum[i]); } A. 2345 B. 1111 C. 1345 D. 1234

A. 2345

Assuming that the user enters 60 as the input, what is the output after running the following code snippet? int num = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num = in.nextInt(); if (num < 10) { System.out.println("Too small!"); } else if (num < 50) { System.out.println("Intermediate!"); } else if (num < 100) { System.out.println("High!"); } else { System.out.println("Too high!"); } A. High! B. Too high! C. Too small! D. Intermediate!

A. High!

Consider the following line of code: int[] somearray = new int[30]; Which one of the following options is a valid line of code for displaying the twenty-eighth element of somearray? A. System.out.println(somearray[27]); B. System.out.println(somearray[28]); C. System.out.println(somearray(28)); D. System.out.println(somearray(27));

A. System.out.println(somearray[27]);

Consider the following code snippet: int number = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); number = in.nextInt(); if (number > 30) { . . . } else if (number > 20) { . . .. } else if (number > 10) { . . . } else { . . . } Assuming that the user input is 40, which block of statements is executed? A. if (number > 30) { . . . } B. else if (number > 10) { . . . } C. else if (number > 20) { . . . } D. else { . . . }

A. if (number > 30) { . . . }

Which of the following is the correct syntax for an if/else statement? A. if (x < 10) { size = "Small"; }else { size = "Medium"; } B. if { size = "Small"; }else (x < 20) { size = "Medium"; } C. if (x < 10); { size = "Small"; }else (x < 20) { size = "Medium"; } D. if (x < 10) { size = "Small"; }else (x < 20) { size = "Medium"; }

A. if (x < 10) { size = "Small"; } else { size = "Medium"; }

Which code snippet calculates the sum of all the even elements in an array values? A.int sum = 0; for (int i = 0; i < values.length; i++){ if ((values[i] % 2) == 0) { sum = sum + values[i]; }} B.int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum++; }} C.int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum++; }} D.int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum = sum + values[i]; }}

A. int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum = sum + values[i]; } }

Identify the correct statement for defining (declaring and creating) an integer array named numarray of ten elements. A. int[] numarray = new int[10]; B. int numarray[10]; C. int[10] numarray; D. int[] numarray = new int[9];

A. int[] numarray = new int[10];

Insert the missing code in the following code fragment. This fragment is intended to read a file and write to a file. public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = _____________; . . . } A. new PrintWriter(outputFileName) B. new Scanner(outputFileName) C. new PrintWriter(outputFile) D. new Scanner(outputFile)

A. new PrintWriter(outputFileName)

What is the output of the the value variable at the end of execution of the given code snippet? public static void main(String[] args) { int value = 3; value = value - 2 * value; value++; System.out.println(value); } A. -2 B. 0 C. 2 D. 4

A. -2

What output is produced by these statements? String name = "Joanne Hunt"; System.out.println(name.length()); A. 11 B. 10 C. 9 D. 8

A. 11

Assuming the numeric sum of 8 and 12 should be displayed, what kind of error is created by the following code snippet? System.out.print("The sum of 8 and 12 is "); System.out.println("8 + 12"); A. Logic error: the program does not produce the desired result B. No error: the code is correct C. Exception: the statement will generate an exception D. Syntax error: the code will not compile

A. Logic error: The program does not produce the desired result

What is the purpose of the following algorithm, written in pseudocode? num = 0 Repeat the following steps 10 times: Input var1 If var1 > num num = var1 Print num A. To find the highest among 10 numbers B. To print out the 10 numbers C. To find the smallest among 10 numbers D. To search for a particular number among 10 numbers

A. To find the highest among 10 numbers

How many times does the code snippet given below display "Loop Execution"? int i = 1; while (i != 10) { System.out.println ("Loop Execution"); i++; } A. 10 times B. 9 times C. Infinite times D. 8 times

B. 9 times

Which of the following is the correct syntax for creating a File object? A. File inFile = File("input.txt"); B. File inFile = new File("input.txt"); C. File inFile = File.open("input.txt"); D. File inFile = new File.open("input.txt");

B. File inFile = new File("input.txt");

When the order of the elements is unimportant, what is the most efficient way to remove an element from a partially-filled array? A. Delete the element and move each element after that one to a lower index. B. Replace the element to be deleted with the last element in the array. C. Replace the element to be deleted with the first element in the array. D. Replace the element with the next element.

B. Replace the element to be deleted with the last element in the array.

Consider the following code snippet: public class Employee { private String empName; public String getEmpName() { . . . } } Which of the following statements is correct? A. The getEmpName method cannot be accessed at all. B. The getEmpName method can be accessed by any client/test class of an Employee object. C. The getEmpName method can be accessed only by methods of another class. D. The getEmpName method can be accessed only by methods of the Employee class.

B. The getEmpName method can be accessed by any client/test class of an Employee object.

Which one of the following statements can be used to get the fifth character from a String str? A. char c = str.charAt(5); B. char c = str.charAt(4); C. char c = str[5]; D. char c = str[4];

B. char c = str.charAt(4);

Which of the following code snippets can be used for defining a method that does not return a value? The method should accept a string and then display the string followed by "And that's all folks!" on a separate line. A. public static String displayMessage(String str){System.out.println(str);System.out.println("And that's all folks!");} B. public static void displayMessage(String str){System.out.println(str);System.out.println("And that's all folks!");} C. public static void displayMessage(String str){System.out.println(str);System.out.println("And that's all folks!");return str;} D. public static void displayMessage(){System.out.println(str);System.out.println("And that's all folks!");}

B. public static void displayMessage(String str) { System.out.println(str); System.out.println("And that's all folks!"); }

Consider the following line of code for calling a method named func1: func1(listData, varData); Which one of the following method headers is valid for func1, where listData is an integer array list and varData is an integer variable? A. public static void func1(int vdata, ArrayList<Integer> ldata) B. public static void func1(ArrayList<Integer> ldata, int vdata) C. public static void func1(Integer[] ldata, int vdata) D. public static void func1(int[] ldata, int vdata)

B. public static void func1(ArrayList<Integer> ldata, int vdata)

Assuming that the user provides 303 as input, what is the output of the following code snippet? int x; int y; Scanner in = new Scanner(System.in); x = 0; System.out.print("Please enter a number: "); y = in.nextInt(); if (y > 300) { x = y; } else { x = 0; } System.out.println("x: " + x); A. x: 0 B. x: 303 C. x: 300 D. There is no output due to compilation errors.

B. x: 303

Assuming that the user provides 303 as input, what is the output of the following code snippet? int x; int y; x = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); y = in.nextInt(); if (y > 300) { x = y; } else { x = 0; } System.out.println("x: " + x); A. x: 0 B. x: 303 C. x: 300 D. There is no output due to compilation errors.

B. x: 303

What is the output of the following code snippet? System.out.print(4 + 4); System.out.print(12); A. 20 B. 812 C. 4 + 412 D. 4412

B. 812

Which Java statement prints a blank line? A. System.out.Println(); B. System.out.println(); C. public static void main(String[] args) D. System.out.print();

B. System.outprintln();

What is wrong with the following code snippet? public class Area { public static void main(String[] args) { int width = 10; height = 20.00; System.out.println("area = " + (width * height)); } } A. The code snippet uses an uninitialized variable. B. The code snippet uses an undeclared variable. C. The code snippet attempts to assign a floating-point value to an integer variable. D. The code snippet attempts to add a number to a string variable.

B. The code snippet uses an undeclared variable.

The enhanced for loop ... A. is convenient for traversing elements in a partially filled array B. is only used for arrays of integers C. is convenient for traversing all elements in an array D. is used to initialize all array elements to a common value

C. is convenient for traversing all elements in an array

Insert the missing code in the following code fragment. This fragment is intended to read an input file. public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = new File(inputFileName); Scanner in = _______________; . . . } A. new Scanner(inputFileName) B. new Scanner(outputFileName) C. new Scanner(inputFile) D. new Scanner(System.in)

C. new Scanner(inputFile)

Suppose you wish to write a method that returns the sum of the elements in the partially filled array myArray. Which is a reasonable method header? A. public static int sum(int[] values, int size, int currSize) B. public static int sum(int[] values) C. public static int sum(int[] values, int currSize) D. public static int sum()

C. public static int sum(int[] values, int currSize)

Evaluate the pseudocode below to calculate the payment (pmt) with the following test values. What is the final output? The total number of hours worked (workingHours) = 50 The rate paid for hourly work (rate) = 10 Input workingHours. Input rate. pmt = workingHours * rate (note: '*' is the Java multiplication operator) If workingHours > 45, then extraHours = workingHours - 45 extraPmt = extraHours * rate * 2 pmt = pmt + extraPmt Output pmt A. 1,000 B. 500 C. 600 D. 400

C. 600

What is the output of the following code snippet? public static void main(String[] args) { double a; a = Math.sqrt(9.0) + Math.sqrt(16.0); System.out.println(a); } A. 25.0 B. 337.0 C. 7.0 D. 19.0

C. 7.0

What is the output of the following code snippet? System.out.print("Hello");System.out.println("Good Day!"); A. Hello Good Day! B. HelloGood Day! C. HelloGood Day! D. HelloGoodDay!

C. HelloGood Day!

What does the following statement sequence print? String str = "Harry"; int n = str.length(); String mystery = str.substring(0, 1) + str.substring(n - 2, n); System.out.println(mystery); A. Ha B. Har C. Hry D. Hy

C. Hry

UML Supermarket has different ways of awarding discounts to its customers for each purchase they make. A 10 percent discount is given on the total value of the purchase. In addition, a standard loyalty discount is given if customers have a permanent customer card. Your program should indicate the amount payable by the customer after the discounts. Identify the inputs that the program requires from these options: I. The discount percentage II. The total value of the purchase III. The loyalty-discount amount IV. The customer card number V. The amount payable after discount A. I, II, and III B. I and III C. II and IV D. II, IV, and V

C. II and IV

A Java class with the name Printer has to be saved using the source file name: A. Printer.txt B. printer.java C. Printer.java D. output.java

C. Printer.java

Which one of the following code snippets compiles without errors and displays the output "Hello Good Day!" on the screen? A. System.out.print("Hello "); System.out.println("Good Day!") B. System.out.print("Hello ); System.out.println("Good Day!"); C. System.out.print("Hello "); System.out.println("Good Day!"); D. System.out.print("Hello "); System.out.println(Good Day!");

C. System.out.print("Hello "); System.out.println("Good Day!");

Assuming that the user inputs a value of 25000 for the pay and 10 for the bonus rate in the following code snippet, what is the output? public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter the pay: "); double pay = in.nextDouble(); System.out.print("Enter the bonus rate: "); double bonus = in.nextDouble(); System.out.println("The new pay is " +(pay + pay * (bonus / 100.0))); } A. The new pay is 25000.0 B. The new pay is 25100.0 C. The new pay is 27500.0 D. The new pay is 30000.0

C. The new pay is 27500.0

Assuming import java.util.Scanner;, and that the user inputs a values of 30 for the price and 10 for the discount rate in the following code snippet, what is the output? Scanner in = new Scanner(System.in); System.out.print("Enter the price: "); double price = in.nextDouble(); System.out.print("Enter the discount rate: "); double discount = in.nextDouble(); System.out.print("The new price is "); System.out.println(price - price * (discount / 100.0)); A. The new price is 30 B. The new price is 20 C. The new price is 27.0 D. The new price is 33.0

C. The new price is 27.0

These two lines of code do not produce the same output. Why? System.out.println(7 + 3); System.out.println("7 + 3"); A. Arithmetic calculations cannot take place within the println method call. B. In fact, the two statements do produce the same output. C. The quotes cause the second expression to be treated as a string. D. Because there are no escape characters.

C. The quotes cause the second expression to be treated as a string.

What is the output of the following code snippet? public static void main(String[] args) { String str1; str1 = "I LOVE MY COUNTRY"; String str2 = str1.substring(4, 9); System.out.println(str2); } A. I LOV B. OVE M C. VE MY D. V

C. VE MY

What will be the value inside the variables a and b after the given set of assignments? int a = 20; int b = 10; a = (a + b) / 2; b = a; a++; // same as a = a + 1; A. a = 15, b = 16 B. a = 16, b = 16 C. a = 16, b = 15 D. a = 15, b = 15

C. a = 16, b = 15

Which of the following options declares a float variable? A. Float age; B. flt age; C. float age; D. age: float;

C. float age;

What is the output of the following code snippet? int num = 100; if (num < 100) { if (num < 50) { num = num - 5; } else { num = num ? 10; } } else { if (num > 150) { num = num + 5; } else { num = num + 10; } } System.out.println(num); A. 95 B. 100 C. 105 D. 110

D. 110

Assuming that a user enters 10, 20, and 30 as input values, what is the output of the following code snippet? int num1 = 0; int num2 = 0; int num3 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); System.out.print("Enter a number: "); num3 = in.nextInt(); if (num1 > num2) { if (num1 > num3) { System.out.println(num1); } else { System.out.println(num3); } } else { if (num2 > num3) { System.out.println(num2); } else { System.out.println(num3); } } A. 10 B. 20 C. 0 D. 30

D. 30

Which of the following statements about Java exception handling is correct? A. The main method of a Java program will handle any error encountered in the program. B. Statements that may cause an exception should be placed within a catch block. C. Statements that may cause an exception should be placed within a throws block. D. Statements that may cause an exception should be placed within a try block.

D. Statements that may cause an exception should be placed within a try block.

Which option represents a legal call to the method square()? public static String square(int a){return "Commencing";} A. int a = square(4); B. String a = square("help"); C. double a = square(4.0); D. String a = square(4);

D. String a = square(4);

What is the problem with the code snippet below? public static String val() { String result = "candy"; return; } . . . // Using method val() System.out.println("The value is: " + val()); A. The use of val in the System.out.println statement is illegal. B. The method val does not have any parameter variables. C. The String data type cannot be returned from a method. D. The method val does not have a return value.

D. The method val does not have a return value.

What is the result of the following statement? String s = "You" + "had" + "me" + "at" + "hello"; A. The string s has the following value: "You had me at "hello" B. The statement results in an error because the + operator can be used only with numbers C. The statement results in an error because the + operation cannot be performed on string literals D. The string s has the following value: "Youhadmeathello"

D. The string s has the following value: "Youhadmeathello"

Consider the following code snippet: throw new IllegalArgumentException("This operation is not allowed!"); Which of the following statements about this code is correct? A. This code constructs an object of type IllegalArgumentException and reserves it for future use. B. This code throws an existing IllegalArgumentException object. C. This code will not compile. D. This code constructs an object of type IllegalArgumentException and throws the object.

D. This code constructs an object of type IllegalArgumentException and throws the object.

Which code snippet finds the largest value in an array that is only partially full? A.double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] < largest) { largest = values[i]; }} B.double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; }} C.double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] < largest) { largest = values[i]; }} D.double largest = values[0]; for (int i = 1; i < currentSize; i++) { if (values[i] > largest) { largest = values[i]; }}

D. double largest = values[0]; for (int i = 1; i < currentSize; i++) { if (values[i] > largest) { largest = values[i]; } }

You need to write a method that calculates the shipping cost for an appliance, which depends on the item's 3D dimensions and weight. What should be the parameters variables and their data types for this method? A. double size, double weight B. double size, double weight, double price C. double size, double weight, double shippingCost D. double width, double height, double depth, double weight

D. double width, double height, double depth, double weight

Complete the following code snippet with the correct enhanced for loop so it iterates over the array without using an index variable. String[] arr = { "abc", "def", "ghi", "jkl" }; ___________________ { System.out.print(str); } A. for (str : String arr) B. for (arr[] : str) C. for (str[] : arr) D. for (String str : arr)

D. for (String str : arr)

What are the values of i and j after the following code fragment runs? int i = 60; int j = 50; int count = 0; while (count < 5) { i = i + i; i = i + 1; j = j - 1; j = j - j; count++; } System.out.println("i=" + i + ", j=" + j); A. i = 1951, j = 45 B. i = 65, j = 45 C. i = 65, j = 1 D. i = 1951, j = 0

D. i = 1951, j = 0

How do you extract the first 5 characters from the String str? A. substring(str, 5) B. substring.str(0, 5) C. str.substring(5) D. str.substring(0, 5)

D. str.substring(0, 5)

Assuming that a user enters 45, 78, and then 12, what is the output of the following code snippet? int num1 = 0; int num2 = 0; int num3 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); System.out.print("Enter a number: "); num3 = in.nextInt(); if (!(num1 > num2 && num1 > num3)) { System.out.println(num1); } else if (!(num2 > num1 && num2 > num3)) { System.out.println(num2); } else if (!(num3 > num1 && num3 > num2)) { System.out.println(num3); } A. 78 B. There is no output due to compilation errors. C. 12 D. 45

D. 45

Consider the following code snippet: int cnt = 0; int[][] numarray = new int[2][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { numarray[j][i] = cnt;cnt++; } } A. 3 B. 4 C. 2 D. 5

D. 5

What is the output of the following code snippet? public static int check(ArrayList<Integer> listData) { int sum = 0; for (int i = 0; i < listData.size(); i++) { sum = sum + listData.get(i); } return sum; } public static void main(String[] args) { ArrayList<Integer> vdata = new ArrayList<Integer>(); int rsum; for (int cnt = 0; cnt < 3; cnt++) { vdata.add(cnt + 1); } rsum = check(vdata); System.out.println(rsum); } A. 2 B. 3 C. 4 D. 6

D. 6

What is the output after running the following code snippet? int number = 600; if (number < 200) { System.out.println("Low spender"); } else if (number < 500) { System.out.println("Spending in moderation"); } else if (number < 1000) { System.out.println("Above average!"); } else { System.out.println("High Roller!"); } A. Low spender B. Spending in moderation C. High Roller! D. Above average!

D. Above average!

What is the result of the following code snippet? public static void main(String[] args) { double circleRadius; double circleVolume = 22 / 7 * circleRadius * circleRadius; System.out.println(circleVolume); } A. 0 B. 3.14 C. 6.28 D. compile-time error

D. compile-time error

Which statement starts the declaration of a class in Java? A. public static void main(String[] args) B. System.out.println("Hello, World!"); C. This is a new Java class D. public class Classname

D. public class Classname

Write one or more Java statements to output the values of the integer variables numberOfHours, numberOfMinutes, time1 and time2 as, for example: There is a difference of 9 hours and 15 minutes between 100 and 1050. In this example, numberOfHours has the value 9, numberOfMinutes has the value 15, time1 has the value 100, and time2 has the value 1050.

System.out.print("There is a difference of "); System.out.print(numberOfHours); System.out.print(" hours and "); System.out.print(numberOfMinutes); System.out.print(" minutes between "); System.out.print(time1); System.out.print(" and "); System.out.print(time2); System.out.println(".");

Describe, in as much detail as possible, what the following method returns: static int getInput() { Scanner kbd = new Scanner(System.in); // Integer.MIN_VALUE is the smallest integer value defined in the Java Language int result = Integer.MIN_VALUE; int input; boolean done = false; while (!done) { System.out.print("Enter a number ('quit' to end): "); if (kbd.hasNextInt()) { input = kbd.nextInt(); if (input > result) { result = input; } } else { done = true; } // end while return result; }

This method allows the user to input any number of integer values, until "quit" (or any non-integer) is entered. The method then returns the largest integer input by the user.

Write Java variable declarations for each of the following: i. an integer variable for the number of hours ii. a floating-point variable for the cost of a train ticket iii. a floating-point variable for the distance from home to work iv. an integer variable for the number of people attending a meeting v. a floating-point variable for the height of a house

i. int numberOfHours; ii. double trainTicketCost; iii. double distanceFromHomeToWork; iv. int peopleInAttendance; v. double houseHeight;

Assuming import java.util.Scanner;, and the following variable declaration: Scanner in = new Scanner(System.in); Write an input statement for each of the five (5) variables declared in the previous question.

i. numberOfHours = in.nextInt(); ii. trainTicketCost = in.nextDouble(); iii. distanceFromHomeToWork = in.nextDouble(); iv. peopleInAttendance = in.nextInt(); v. houseHeight = in.nextDouble();

Write a Java statement that calculates timeDiff as the absolute value of the difference of mins1 and mins2. You can assume that timeDiff, mins1 and mins2 have all been declared as int variables, and that mins1 and mins2 have been assigned values.

timeDiff = Math.abs(mins1-mins2);

Write a Java statement for the following mathematical expression: z = sqrt(x^2 + y^2) Note: You can assume x, y and z are all declared as double variables and that x and y have been assigned values.

z = Math.sqrt(Math.pow(x,2) + Math.pow(y,2));

Imagine you are planning to buy a new cell phone. You are considering two cell phones. These cell phones have different purchase prices. Each mobile service provider charges a different rate for each minute that the cell phone is used. To determine which cell phone is the better buy, you need to develop an algorithm to calculate the total cost of purchasing and using each cell phone. What are all the inputs needed for this algorithm? A. The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes provided with each cell phone B. The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes you would use the cell phone C. The cost of each cell phone and the number of minutes provided with each cell phone D. The cost of each cell phone and the rate for each minute for each cell phone

B. The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes you would use the cell phone

What is the sentinel value in the following code snippet? public static void main(String[] args) { int age = 0; int sumOfAges = 0; int stop = 1; Scanner reader = new Scanner(System.in); System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); while (age != -1) { sumOfAges = sumOfAges + age; System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); } System.out.println("Sum of ages " + sumOfAges); return 0; } A. 0 B. 1 C. -1 D. 2

C. -1

How many times will the following loop run? int i = 0; while (i < 10) { System.out.println(i); i++; } A. 0 B. 8 C. 10 D. 9

C. 10

What is the output of the following code snippet if the input is 25? int i = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); i = in.nextInt(); if (i > 25) { i++; // same as i = i + 1; } else { i--; // same as i = i - 1; } System.out.print(i); A. 26 B. 27 C. 24 D. 25

C. 24

What is the output of the following code snippet? int[] myarray = { 10, 20, 30, 40, 50 }; System.out.print(myarray[2]); System.out.print(myarray[3]); A. 1050 B. 2030 C. 3040 D. 4050

C. 3040

Given the following class definition, which of the following are considered part of the class's public interface? public class CashRegister { public static final double DIME_VALUE = 0.1; private static int objectCounter; public void updateDimes(int dimes) {. . .} private boolean updateCounter(int counter) {. . .} } A. objectCounter and updateCounter B. DIME_VALUE and objectCounter C. DIME_VALUE and updateDimes D. updateDimes and updateCounter

C. DIME_VALUE and updateDimes

Which of the following statements about using a PrintWriter object is correct? A. If the output file already exists, the new data will be appended to the end of the file. B. If the output file does not exist, a FileNotFoundException will occur. C. If the output file already exists, the existing data will be discarded before new data are written into the file. D. If the output file does not exist, an IllegalArgumentException will occur.

C. If the output file already exists, the existing data will be discarded before new data are written into the file.

Consider the following code snippet: public static void check(ArrayList<Integer> chknum1) { int cnt = 0; for(int i = 0; i < chknum1.size(); i++) { if(chknum1.get(i) == 0) { cnt++; } } System.out.println("The total 0 values in the list are: " + cnt); } Which one of the following is true about the check method in the given code snippet? A. The check method counts all the elements with value 0 in an array list passed as a parameter to a method and also returns the count. B. The check method adds 0 to the elements of an array list as a parameter to a method and also returns the array list. C. The check method counts all the elements with value 0 in an array list passed as a parameter to the method. D. The check method removes all the elements with value 0 from an array list passed as a parameter to the method.

C. The check method counts all the elements with value 0 in an array list passed as a parameter to the method.

Consider the following code snippet: public class Coin { private String coinName; . . . } Which of the following statements is correct? A. The coinName variable can be accessed by any client/test class of a Coin object. B. The coinName variable cannot be accessed at all because it is private. C. The coinName variable can be accessed only by methods of the Coin class. D. The coinName variable can be accessed only by methods of another class.

C. The coinName variable can be accessed only by methods of the Coin class.

Consider the following code snippet: boolean attendance = true;boolean failed = false; Which of the following expressions evaluates to true? A. attendance == failed B. attendance == "true" C. attendance || failed D. attendance && failed

C. attendance || failed

Which code snippet will output "Yes!" when two strings s1 and s2 are equal? A. if (s1 == s2) { System.out.println("Yes!"); } B. if (s1 = s2) { System.out.println("Yes!"); } C. if (s1.equals(s2)) { System.out.println("Yes!"); } D. if (s1 equals s2) { System.out.println("Yes!"); }

C. if (s1.equals(s2)) { System.out.println("Yes!"); }

Write Java code that repeatedly gets a double value as user input, stopping when non-numeric input is entered, and outputting the smallest (minimum) value entered. If no values are entered, "No input" is output. Note: you can assume import java.util.Scanner;

Scanner in = new Scanner(System.in); double smallest = 0; boolean hasInput = false; System.out.println ("Enter some numbers, 'quit' to end:"); while (in.hasNextDouble()) { double input = in.nextDouble(); if (hasInput) { if (input < smallest) { smallest = input; } } else // no input yet { smallest = input; hasInput = true; } } // end while loop System.out.printf("The smallest input is %.2f\n", smallest);

What is short-circuit evaluation of Boolean expressions?

Short-circuit evaluation is a mechanism in Java that allows the early termination of the evaluation of a compound Boolean expression. This occurs when two Boolean expressions are joined by the && operator when the first expression evaluates to false. The evaluation short-circuits because no matter what the value of the second expression is, the expression will evaluate to false. When two Boolean expressions are joined by the || operator, if the first expression evaluates to true, then the evaluation will short circuit because the expression will always evaluate to true no matter what the second expression evaluates to.

Assume we want to write a scheduling program. We decide to define a class named Appointment that contains instance variables for: startTime, endTime, dayOfWeek (valid values are "Sunday" through "Saturday"), and a date which consists of: a month (valid values are "January" through "December"), a day number (integer) a year number (integer) Both times can be expressed in military time (hhmm), so that we can use integers to represent the time; hh is the number of hours (0-23), while mm is the number of minutes (0-59). We start by declaring the instance variables for the Appointment class so that they are only accessible from instance methods of the same class: private int startTime; private int endTime; private String dayOfWeek; // valid strings: "Sunday", "Monday", ..., "Saturday" private String month; // valid strings: "January", "February", ..., "December private int dayNumber; private int yearNumber; Write a Java definition/implementation for the boolean instance method validDayOfWeek, which returns true if the dayOfWeek instance variable is one of the days "Sunday" through "Saturday", and false otherwise.

public boolean validDayOfWeek() { return ( dayOfWeek.equals("Sunday") || dayOfWeek.equals("Monday") || dayOfWeek.equals("Tuesday") || dayOfWeek.equals("Wednesday") || dayOfWeek.equals("Thursday") || dayOfWeek.equals("Friday") || dayOfWeek.equals("Saturday") ); }

Assume we want to write a scheduling program. We decide to define a class named Appointment that contains instance variables for: startTime, endTime, dayOfWeek (valid values are "Sunday" through "Saturday"), and a date which consists of: a month (valid values are "January" through "December"), a day number (integer) a year number (integer) Both times can be expressed in military time (hhmm), so that we can use integers to represent the time; hh is the number of hours (0-23), while mm is the number of minutes (0-59). We start by declaring the instance variables for the Appointment class so that they are only accessible from instance methods of the same class: private int startTime; private int endTime; private String dayOfWeek; // valid strings: "Sunday", "Monday", ..., "Saturday" private String month; // valid strings: "January", "February", ..., "December private int dayNumber; private int yearNumber; Write a Java definition/implementation of the boolean instance method validTimes, which returns true if the startTime instance variable comes before the endTime instance variable, and false otherwise.

public boolean validTimes() { return startTime < endTime; }

Write an implementation for the Java method isName: /* isName(String) → boolean method is given a String; method indicates whether or not the String is a name (i.e., a proper noun): ● first character is an upper-case letter ● all other characters are lower-case letters ex: isName("John") → true isName("mary") → false isName("") → false */ Hints: i. use a loop and the String method charAt(i) to access the character at each index i of the String parameter ii. the pre-defined static method boolean Character.isUpperCase(c) returns true if the given char c is an upper-case letter, and false otherwise iii. the pre-defined static method boolean Character.isLowerCase(c) returns true if the given char c is a lower-case letter, and false otherwise

public static boolean isName(String text) { if (text.length() == 0) { return false; } char nextLetter = text.charAt(0); boolean result = Character.isUpperCase(nextLetter); int index = 1; while (result && index < text.length()) { nextLetter = text.charAt(index); result = Character.isLowerCase(nextLetter); index = index + 1; } return result; }

Write an implementation of the following Java method; it is passed a String and returns the character at (roughly) at the middle of the String. /* * middleChar(String) -> char * * method returns the character in the middle of the given String * method assumes the given String has at least 3 characters * * ex: middleChar("abcde") -> 'c' * ex: middleChar("abcdef") -> 'd' */

public static char middleChar(String s) { int len = s.length(); char c = s.charAt(len/2); return c; } // end middleChar

Write an implementation of the following Java method, which is passed four integers and returns their average. /* * average(int, int, int, int) -> double * * method returns the average of the 4 given integers * * ex: average(80, 90, 95, 100) -> 91.25 */

public static double average(int a, int b, int c, int d) { int sum = a+b+c+d; double result = sum/4.0; // can't use sum/4 here (why?) return result; } // end average

Write an implementation of the following Java method. It prompts the user with the given String, and returns the user input (a double value). /* * readDouble(String prompt) -> double * * displays the prompt String to the user * method gets and returns double user input */

public static double readDouble(String prompt) { Scanner in = new Scanner(System.in); double result; System.out.print(prompt); result = in.nextDouble(); return result; } // end readDouble

Write a definition/implementation for a Java method sumList that is passed a Double ArrayList as its parameter and returns the sum of the values contained within the ArrayList. Note that the method should throw an IllegalArgumentException with an appropriate message whenever a null argument is passed to it.

public static double sumList(ArrayList<Double> values) { if (values == null) { throw new IllegalArgumentException("null values list"); } double sum = 0; for (double value : values) { sum += value; // same as sum = sum + value; } // end for loop return sum; } // end sumList

Write an implementation of the following Java method, using any type of Java loop. /* sumSeries(int, int) -> double method is passed two integers n and m as its parameter values method returns the calculation of the following series for n > 0: sumSeries(n, m) -> The sum from t = 1 to n of (i^m) = 1 + 2^m + 3^m + ... + n^m method returns 0 whenever n is non-positive */

public static double sumSeries(int n, int m) { double sum = 0; for (int i = 1; i<=n; i++) { sum += Math.pow(i, m); } return sum; }

Write an definition/implementation of the following Java method. It is passed four integers, and returns the largest of these: /* * largestOf(int, int, int, int) -> int * * method is given four integers * method produces the largest of the four integers * * ex: * largestOf(4, 9, 2, 5) -> 9 * largestOf(4, 0, 2, 5) -> 5 * largestOf(-4, -9, -2, -5) -> -2 * largestOf(0, 0, 0, 0) -> 0 */

public static int largestOf(int a, int b, int c, int d) { int result = Math.max(a, b); result = Math.max(max, c); result = Math.max(max, d); return result; }

Implement the Java method sumAllEvens: sumAllEvens(int) -> int method is given an integer method returns the sum of the even digits of the absolute value of the given integer ex: sumAllEvens(23766) -> 14 ex: sumAllEvens(0) -> 0 ex: sumAllEvens(-23766) -> 14

public static int sumAllEvens(int number) { int result = 0; int digit; if (number < 0) { number=number*-1; } while (number > 0) { digit = number%10; if (digit%2 == 0) { result = result + digit; } number = number/10; } // end loop return result;} // end sumAllEvens


Set pelajaran terkait

clase 3 License Expiration and Renewal

View Set

PS101 Dunne Exam 2 - Boston University

View Set

Fr1 2.1 #2 Which subject pronoun replaces...?

View Set

OB Chap 26 The child with a cardiovascular disorder

View Set

OB/PEDS Ch 15: Fetal Assessment during Labor

View Set