CMSC FINAl

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the output of the following two code segments? 1. System.out.println(45 / 7 > 5 || 2 / 0 > 9); 1. System.out.println(33 + 54 > 67 && 6 / 0 < 7);

1. true 2. error

Consider the following code segment. x = 2 y = 3 z = 5 z = y y = x * z x = z z = y x = y + z z = x / y y = x After the above code is executed, what is the value of y?

12

Answer the question about the following code segment. int i = 2; do { System.out.print(i + "#"); i--; } while (i >= 3); What is the output of the loop? ______________

2#

Bonus (+2 points): What is the value of m after this operation? int b = 5; int m = 20; m -= 6 + 2 * 3 + ++b - 8 / 2;

6

List the symbols for the relational operators that can be used to compare primitive data types in Java.

== != > >= < <=

Which of these best describes the relationship between classes and objects?

Classes are like the a blueprint, they define objects.

A part of a program that contains information about the program but has no effect when the program runs is called a ______________________.

Comment

Write the algorithm for a program that will assign a BMI status to patients. The doctor will enter a BMI index value and the program will display the BMI status. Use the BMI chart provided.

Enter BMI_IndexValue IF BMI_IndexValue > 29.9Output "Obese" ELSE IF BMI_IndexValue >= 25Output "Overweight" ELSE IF BMI_IndexValue >= 18.5Output "Normal weight" ELSEOutput "Underweight"

Write an algorithm for a program that will ask the user for the number of players they have. The program will then ask for each player's name and dive score, and, at the end of the input, will display the player's name with the highest score along with their score. You do not need to worry about tie scores. (You are not allowed to use arrays for this solution.)

Enter numPlayers Set count to 1 Enter name Set highName to name Enter score Set highScore to score WHILE (count < numPlayers)Enter name and scoreSet highScore = scoreSet highName = nameIF score > highScoreEND IFSet count = count + 1 Display highName

Write the pseudocode for a program that will read in two files, one containing a team name and a numeric score for that team, and a second for output. The program will output the team with the lowest score and the score for that team to the inputted output file. Here is a sample of the file's data: Colts,27 Giants,41 Panthers,24

Enter two filenames Open the first file Set LowTeam to the first team read from the file Set LowScore to the first score read from the file WHILE (there are more lines to readRead in a line of dataSplit the line into team and scoreIF(lowScore > score)lowTeam = teamlowScore = scoreEND IF END WHILE Create/open the output file Output lowTeam and lowScore to the output file Close the output file

The class name does not have to be the same as the file name

False

How would you print out the value below rounded to two decimal places: double total = 534.234326;

System.out.printf("%.2f", total);

Which of the following lines of code correctly writes "Hello" to the screen.

System.out.println("Hello");

Given the function definition: DEFINE add(a, b, c) sum = 0 IF ((a < b) AND (a < c)) THEN sum = b + c RETURN sum avg = sum / 3 ELSE IF ((b < a) AND (b < c)) THEN sum = a + c RETURN sum avg = sum / 3 ELSE sum = a + b RETURN sum avg = sum / 3 ENDIF sum += 10 avg = sum / 3 ENDDEF Which of the following statements is true after the execution of the function call: add(5, 3, 2)

The avg assignment statement is never reached

What is the purpose of the constructor in a class?

The constructor is used to construct objects of a particular class.

What is written to the output file from the following code if the input file contains the values: 2 4? import java.io.File;import java.io.FileNotFoundException;import java.io.PrintWriter;import java.util.Scanner;public class Items{public static void main(String[] args) throws FileNotFoundException{Scanner console = new Scanner(System.in);System.out.print("Input file: ");String inputFileName = console.next();System.out.print("Output file: ");String outputFileName = console.next();File inputFile = new File(inputFileName);Scanner in = new Scanner(inputFile);PrintWriter out = new PrintWriter(outputFileName);double total = 0;while (in.hasNext()){double price = in.nextDouble();price *= 10;out.printf("The increase is: %10.1f%n", price);total += price;out.printf("The total increase is: %10.1f%n", total); }in.close();out.close();}}

The increase is: 20.0 The total increase is: 20.0 The increase is: 40.0 The total increase is: 60.0

Discuss what the memory diagram looks like when the main program calls performAction(num) paying special attention to the value of nums and data. public class Test {public static void main(String[] args) {int[] nums = {1, 2, 3, 4};performAction(nums);System.out.println(Arrays.toString(nums));}public static void performAction(int [] data) {for (int i =0; i < data.length; i++) {data[i] = i * 5;}}}

The main method has a variable called num that contains the reference to the location of an int array in memory. When the main method calls performAction(nums) it passes that reference to the method performAction. performAction assigns the reference to the variable data. When the data variable changes the value of the array, this is the same array that nums points to, so the values nums prints change as well.

Given the function definition for computing the displacement of an object: DEFINE calculate (a, b, c) solution = a * c + 0.5 * b * c * c RETURN solution ENDDEF And the additional pseudocode x = 3 y = 12 z = 9 solution = calculate(x, y, z) Which of the following statements is false during the call to calculate(x, y, z) has completed execution?

The order of inputs to the function call is unimportant; the function definition declares how the inputs are used. e.g., calculate(x, y, z) == calculate(y, x, z).

Logic errors are the hardest errors to find. T/F

True

What are the two values that a boolean variable can have?

True False

Write the code to declare and initialize a variable called initial that is set to the character Y.

char initial = 'Y'

Given the following declaration statement, write a statement that increments the value in the variable count. int count = 0;

count++

The process of finding and removing errors is called: __________________.

debugging

Write a constant statement to hold the value of discount, which is 15%. ________________________

final double discount

Name two primitive Java data types that represent floating point numbers.

float, double

write an enhanced for loop or foreach loop, that will output the values of the array below, one on each line. double[] values = {4.56,23.75,2.45,19.34,21.54}

for(double r: values) { System.out.println(e)}

Write the if statement that returns true if the int value of a is not in the range between 2 and 6, inclusively. a has been initialized.

if ((a < 2) || (a > 6)) if !(a>=2&&a<=6) if !(a >= 2 && a <= 6) if (a < 2 || a > 6) if (a<2||a>6)

Write a conditional statement that stores true in a boolean variable, happy, if the int variable result is greater than or equal to the int variable positiveRange. Otherwise, store false in the boolean variable, happy. You may assume that all variables have been declared and initialized.

if (result >= positiveRange) { happy = true; } else { happy = false; }

Name two primitive Java data types that represent whole numbers.

int, byte, short, long

Bonus(+2): Which answer best explains how this code snippet would or would not work? int k = 1; int i = 1; while(i < 5) k = i * 2; System.out.println(i); i++;

it would work and would infinitely increase k by i * 2

Write the code to declare and initialize a long variable called size with the value of 956345267356.

long size= 956345267356L;

What is stored in the memory location of the variable below? String s = "Hello"; Choose all that apply

memory address a reference

Which of the following answers best describes how space in memory is allocated in the code below Pillow myPillow; Bed myBed = new Bed();

myPillow variable does not reference a Pillow object and myBed variable references a Bed object

What should the values of x and y be in order to fill all the elements of the following array with values of -1? int[] myArray = new int[10]; int i; int x; int y; for (i = x; i <= y; i++){ myArray[i] = -1; }

x = 0, y = the length of myArray

What should the values of x and y be in order to fill all the elements of the following array with values of 2? int[] myArray = new int[10]; int i; int x; int y; for (i = x; i < y; i++){ myArray[i] = 2; }

x = 0, y = the length of myArray

Consider the following code segment.r = 5 h = 9 Please select the most correct code fragment that will result in calculating the surface area of a cylinder, given the equation: Surface area = 2PIr^2 + 2PIrh

x = 2 * π * r y = x * r z = h * x surfaceArea = y + z

What values are outputted in the output statement in the main method? public class Test{ public static void main(String[] args){ int[] nums = {1,2,3,4}; preformAction(nums); System.out.println(Arrays.toString(nums)) } public static void preformAction(int[] data) { for (int i = 0; i = data.length; i++){ data[i] = i * 5; } } }

{0,5,10,15}

Create and fill the array with the values that would be stored after the code executes: int[] data = new int [9]; data[5] = 3; data[4] = -5; int x = data[5]; data[x] = 27; data[1] = data[4] + data[3] + data[5];

{1,25,0,27,-5,3,0,0,0}

Create and fill the array that would be stored after the folloiwng code executes: int[] list = {2, -5, 3, -8, 12, 15, -9, 10}; for (int i = 1; i < list.length; i++){ list [i] = list[i] - (list[i] /list[i - 1]); }

{2,-2,3,-5,13,-8,11}

charList=['h','e','l','l','o','w','o','r','l','d']; firstWord = [] secondWord[]; flag = false; FOR i= 0 TO length(charList) BY 1 DO If (*/ missing 1 */) THEN /* missing 2*/ flag = true ELSE /* missing 3 */ END IF

1. charList[i] == 'h' || flag = true 2. secondWord[i.length - (firstWord[i] - charList[i]) 3. firstWord[i] - charList[i]

What does the virtual machine do? Choose all answers that apply.

1. runs the class file 2. runs the byte code

While running a program, it unexpectedly stops. What type of error is that? Choose all answers that apply.

1. runtime 2. logic

State the output of the following code sample: int[][] values = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { values[i][j] = (2*i * 2*j); System.out.print(values[i][j] + " "); } System.out.println(); }

0 0 0 0 0 4 8 12 0 8 16 24 0 12 24 36

Answer the questions about the following code segment. int num = 44; while (num > 4){ num = num % 5; } How many times does this loop execute? What is the value of num when the loop ends?

1. 1 2. 4

Answer the questions about this code segment. int num = 1; int sum = 0; while (num < 4) { sum = sum + 3; num++; } How many times does this loop execute? What is the value of num when the loop ends? What is the value of sum when the loop ends?

1. 3 2. 4 3. 9

What is displayed in the following code segment? int numerator = 34; int denominator = 6; 1. System.out.println(numerator / denominator); 2..out.println(numerator % denominator);

1. 5 2. 4

Explain the steps that need to happen to take code from it being written to it running and producing output.

1. Code is written 2. Code is compiled 3. The byte code is read

For each error shown below match it to the correct output: a compile-time error, run-time error, or no error. 1. System.out.Println("Greetings, Planet Earth!"); 2. System.out.println(4356 / 0); 3. float scale = 7854.345368564323; 4. System.out.println("I love VCU!") 5. Double x = 43.454; 6. System.out.print(45 % 342);

1. Compile-time error 2. run-time error 3. compile-time error 4. compile-time error 5. compile-time error 6. no error

What is the output of the following two code segments? 1. System.out.println(45 / 7 > 15 || 2 / 0 > 9); 2. System.out.println(33 + 54 < 67 && 6 / 0 < 7);

1. Error 2. False

List the three steps that are included in every properly implemented loop structure.

1. Initialize the loop control variable 2. Test the loop control variable 3. Update the loop control variable

What is the output of the following lines of code: 1. System.out.println("Output is " + 5 + 6); 2. System.out.println("Output is " + (5 + 6));

1. Output is 56 2. Output is 11

Find the algorithm for a pizza order program. The program will calculate the total cost of a pizza order. Guests can order small, medium and large pizzas, and no, matter how many toppings, small pizzas cost $9.99, medium pizzas cost $12.99, and large pizzas cost $15.99. The program will also calculate the sales tax of 5.5%. (Remember to correctly handle constants.)

1. Set SMALL_PRICE, MED_PRICE, LARGE_PRICE, and SALES_TAX = 0.055 2. Enter numSmall, numMedium, numLarge 3. Calculate pizzaSubTotal by SMALL_PRICE * numSmall + MED_PRICE * numMedium + LARGE_PRICE * numLarge 4. Calculate total by pizzaSubTotal * (1 + SALES_TAX) 5. Output total

What is a variable? Choose all parts below that are relevant.

1. can change 2. memory location 3. named

Write the code that will determine if the two strings, s1 and s2 are equal.

s2.compareTo(s1) == 0 s2.compareTo(s1)==0 s1.compareTo(s2) == 0 s2.equals(s1) s1.equals(s2) s1.compareTo(s2)==0

Given the function pseudocode definition: DEFINE greet(first, last) greeting = first + " " + last IF (first == "Good") THEN RETURN greeting ENDIF greeting = greeting + "!" PRINTLN greeting RETURN greeting END DEF And the following code statements: banner = "Good morning Bob" greet("Good", "morning") PRINTLN banner What is the output of this code?

Good morning Bob

The command to compile a Java program is: ____________________ Hello.java.

Java

Create the UML Class Diagram for the following class: Polynomial class two double instance variables: numSides and sideLength default constructor parameterized constructor passing in numSides and sideLength accessors and mutators for numSides and sideLength getArea method that calculates and returns the area getPerimeter method that calculates and returns the perimeter toString method to return a string including the area and perimeter of the polynomial

Polynomial - numSides: double - sideLength: double + Polynomial() + Polynomial(numSides: double, sideLength: double) + getNumSides(): double + setNumSides(numSides: double): void + getSideLength(): double + setSideLength(sideLength: double): void + getArea(): double + getPerimeter(): double + toString(): String

Fill in the blanks of the code below : __ __ __ main(__ args){

Public, static, void, String[]

Write the algorithm for the following computer problem: Bear Corporation needs a program to calculate their quarterly assessment fee. They will total the sales for the past quarter (a three month period) and the pay 22% of the total sales as their quarterly assessment fee.

Set ASSESS_PERCENT = 0.22 Enter month1Sales, month2Sales, Month3Sales Calculate totalSales by adding month1Sales, month2Sales, Month3Sales Calculate assessmentFee by totalSales * ASSESS_PERCENT Output assessmentFee

Write a java statement that declares and instantiates an Array of String objects called fruit with the following values: "apple","banana","orange","cherry","grape"

String[] fruit = ("apple","banana","orange","cherry","grape")

What happens in memory when the output statement in the main method? public class Test{ public static void main(String[] args){ int[] nums = {1,2,3,4}; preformAction(nums); System.out.println(Arrays.toString(nums)) } public static void preformAction(int[] data) { for (int i = 0; i = data.length; i++){ data[i] = i * 5; } } }

When the main method calls, it passes the reference to the memory adress of the array to which the variable nums points to the method preformAction. preform action assigns the reference to the variable data. When the data variable changes the value of the array, this is the same array that nums points to, so the values nums print changes as well.

Pseudocode: word = "YPPAH" FOR i = 0 TO length(word) INCREASING BY 1 DO FOR j = 0 TO i INCREASING BY 1 DO PRINT word.charAt(i - j) [Remember that charAt(i) returns the character from the String at position i] ENDFOR PRINTLN "!" ENDFOR What is the output of this pseudocode segment?

Y! PY! PPY! APPY! HAPPY!

What values are outputted in the output statement in the main method? public class Test {public static void main(String[] args) {int[] nums = {1, 2, 3, 4};performAction(nums);System.out.println(Arrays.toString(nums));}public static void performAction(int [] data) {for (int i =0; i < data.length; i++) {data[i] = i * 5;}}}

[5, 10, 15, 20]

What is the value of a, b and c after the following code executes: a = 3 b = 9 c = 5 IF b % a == 0 THEN IF b >= c THEN a = a * a ELSE c = c * c ENDIF ELSE IF c >= a THEN IF b >= c THEN b = b * b ENDIF ELSE c = c * c ENDIF ENDIF IF b % a == 0 THEN a = a + 3 ELSE b = b * 2 ENDIF

a = 12 b = 9 c = 5

Write a method that will return the result of an integer number, which is passed in, raised to the fourth power. Here are method calls and the expected output: quad(2) returns→ 16 quad(-1) returns→ 1 quad(3) returns→ 81

public static int quad(int num) { return num * num * num * num; }

Select the steps for a method that is passed a positive integer value, num. The method will output the numbers starting at 1 going to that value of num passed in with a space separating them. Here is a sample method call and the expected output: listNumbers(5) prints→ 1 2 3 4 5

public static void listNumbers(int num) { for (int i = 1; i <= num; i++) { System.out.print(i + " "); } }

What code will return the string, "Wild", from the string: String s = "Call of the Wild" Choose as many answers as apply.

s.substring(12) s.substring(12, 16)

What code will return the string, "the", from the string: String s = "Call of the Wild" Choose as many answers as apply.

s.substring(8, 11)


Kaugnay na mga set ng pag-aaral

Why a 2022 recession would be unlike any other (core)

View Set

Fluid and Electrolytes questions

View Set

Chapter 1: Into to Psychological Science Attempt 1

View Set

PROPERTY & LIABILITY INSURANCE (Test 3): Chapter 24-33

View Set

Anesthesiology, Intensive Care and Nursing

View Set

OT 518 Unit 1 (Quantitative Research)

View Set

ALU Chapter 13 Coronary Artery Disease

View Set

Chapter 09 Assignment: Managing Human Resources and Diversity

View Set