Part 1. (a) Consider the following code segment: int p = 30; int b; Midterm Practice Problems - answer key Answers appear in boldface. System.out.print( Please enter an integer ); b = kb.nextint(); if (b > p b < 0 ) { p = 2*p; b = b/25; p = 0; b = b%2; Assume the user entered 55. What is the value of variable p after the execution of this program segment? 60 What is the value of variable b after the execution of this program segment? 2 Explanation: since b > p (since 55 >30) the OR evaluates to true, and the if-part is executed. Note, the integer division 55/25 produces 2. (b) What will be printed by the following code segment: int a = 35; int b = 100; boolean flag = false; if (!flag a > b ) System.out.println ( One ); else System.out.println ( Two ); One Explanation:!false is true, so the condition evaluates to true. (c) Consider the following code segment: String mystr = kb.nextline(); int len = mystr.length(); String result; if (len <=3 mystr.charat(0) == Z ) { result = RARE ; result = NOT RARE ; Page 1 of 7
Show values of variables len and result after the execution of this program segment for the following user inputs: user enters Zanzibar len 8 result RARE user enters Moo len 3 result RARE (d) What will be printed by the following code segment? int a = 20; int b = 100; boolean flag = false; if ( b % a == 0 ) flag = true; if (!flag ) { System.out.println ( One ); System.out.println ( Two ); Two Show values of following expressions: b % a 0!flag false (c) Consider the following code segment and show what is printed when it is executed. Show the intermediate values of variables k and s for partial credit. int k = 1; int s = 0; while ( s < 5 ){ System.out.print( * ); if (k % 2 == 1) s = s + k; k++; *****6 9 System.out.println(k); System.out.println(s); Page 2 of 7
Part 2. The following sample solutions present just one way of accomplishing the task. While your could be different, it could nevertheless be correct. (a) Rewrite the following switch statement using if and/or if-else statements. switch (str.charat(0)) { case S : case O : num = 1; break; case T : num = 10; break; default: System.out.println ( Error. ); if (str.charat(0) == 'S' str.charat(0) == 'O'){ num = 1; else if ( str.charat(0) == 'T') { num = 10; System.out.println ("Error."); (b) Complete the following code segment so that it would print the first and the last character of mystr. String mystr = kb.nextline(); System.out.println("first letter is " + mystr.charat(0)); int lastpos = mystr.length() - 1 ; System.out.println("last letter is " + mystr.charat(lastpos)); (c) Write a loop that will compute the sum of all multiples of 3 between 200 and 250 int sum = 0; for (int i = 200; i <= 250; i++ ){ if (i % 3 == 0 ) // i.e. if i is divisible by 3 sum += i; System.out.println(sum); Page 3 of 7
(d) Complete the next segment so that it calculates the monthly interest on the amount of dollars stored in variable cost, corresponding to the yearly interest rate stored in yearlyrate. double cost = kb.nextdouble(); double yearlyrate = kb.nextdouble(); double monthlyrate = yearlyrate/12; double monthlyinterest = cost*monthlyrate; (e) Rewrite the following for loop as an equivalent while loop: for (int p = 0; p<=str.length() 1; p++){ System.out.println(str.charAt(0)); int p = 0; while (p <= str.length() - 1){ System.out.println(str.charAt(0)); p++; (f) Given a word that contains letter a, e.g. flubbergasted produce one that has two letters after the first a capitalized, i.e. flubbergasted. String str = "flubbergasted"; int index = str.indexof("a"); // check if there is an 'a' in str and if it is // at least two positions before the end if (index!= -1 && index + 2 < str.length() ){ String uptoa = str.substring(0, index+1); String twoletters = str.substring(index+1, index+3); String aftertwoletters = str.substring(index+3); String modifiedword = uptoa+twoletters.touppercase()+aftertwoletters; System.out.println(modifiedWord); (g) Assume lines is an array of Strings. Write a code segment that calculates how many elements in lines have length between 3 and 15. // assuming lines is an array of strings int countwords = 0; for(int i = 0; i < lines.length; i++){ int len = lines[i].length(); if (len >= 3 && len <= 15){ countwords++; System.out.println("There were " + countwords + " strings of length btw 3 and 15"); Page 4 of 7
Part 3. Solutions to Problems 1 and 2 are not included here. 3. Write a complete program that computes the number of A s on the test given a list of grades and checks if the grades are entered in the non-decreasing order. The program must at first read the number of grades in the list (n) followed by exactly n numeric grade values. The program must compute and print 1. how many grades were greater or equal to 90, 2. whether or not the grades were entered in non-decreasing order, i.e. if each next grade was equal to or greater than the previous. For example, given the following user input: 5 80 70 90 95 76 (where 5 is the number of grades, and the grades are 80, 70, 90, 95, and 76) the program must print There were 2 A-s, The grades were not entered in non-decreasing order. since there were only two grades equal or greater than 90, and the second grade (70) was lower than the one before it (80). Here s another example. For user input 5 80 82 90 90 99 the output should be There were 3 A-s, The grades were entered in non-decreasing order. Your program doesn t have to contain comments, but must otherwise use good programming style. public class GradeReport{ public static void main (String[] args) { int numgrades; // number of grades in the list System.out.println ("Please enter how many grades"); numgrades = kb.nextint(); int gr; int prevgr; // grade that was just entered // previous grade boolean nondecreasing = true; // flag true iff all // grades so far were //entered in non-decreasing order int numas = 0; // number of A's in the list gr = -1; // set it to 1 so that the first grade // that is entered is greater than prevgr // read and analyze exactly numgrades grades for (int i = 1; i <= numgrades; i++) { // update the previous grade, before reading the next prevgr = gr; System.out.println ("Please enter next grade"); gr = kb.nextint (); if (gr >= 90) Page 5 of 7
numas++; // check if non-decreasing order is violated // by comparing the previous grade to one just entered if (prevgr > gr) { nondecreasing = false; System.out.println ("There were " + numas + " A-s"); if (nondecreasing == true) // same as if (nondecreasing) System.out.println("The grades were entered in non-decreasing order."); else System.out.println("The grades were not entered in nondecreasing order."); 4. Write a complete program that lets a user enter words, computes how many words in the input have the same starting and ending letter. The program must at first read the number of words in the list (n) followed by exactly n words each appearing on a separate line. Then, the program must compute and print how many words start with the same letter as they end with, For example, given the following user input: 5 Shine on you crazy diamond (where 5 is the number of words that follow) the program must print Number of words with matching first and last letter is 1 since there is only one word (diamond) with first letter matching the last, and the word on, for example, is shorter than the previous word Shine. Here s another example. For user input 3 one seven eighteen the output should read Number of words with matching first and last letter is 0 Your program doesn t have to contain comments, but must otherwise use good programming style. public class CalcMatches { public static void main(string[] args) { System.out.println("Please enter how many words in the list"); Page 6 of 7
int n = kb.nextint(); String word = ""; int nummatching = 0; // to store number of words with // matching first/last chars for (int i = 0; i< n; i++){ System.out.println("Please enter the next word"); word = kb.nextline (); // compute the position of last character in word int lastpos = word.length()-1; // check if first and last chars are same if (word.charat(0) == word.charat(lastpos)) nummatching++; // increase nummatching by 1 System.out.println(numMatching); Page 7 of 7