Solutions to CompSci 6 Spring 2008 Test 1 1. PART A A. int B. one C. printed: eDu return value: 4 D. printed: eee return value: 4 E. in Mystery pos is the location of the first 'e' and pos2 is the location of the 2nd 'e'. Mystery prints 3 consecutive characters starting with the first e, and then returns the number of characters from the second e to the end of the string. F. "yes" There is no second e, so pos2 will equal -1. It crashes because substring(-1) does not exist. 1. PART B A. x and num B. int C. 9 D. Mystery2 returns the sum of the numbers less then 6 in the arrayList E. ArrayList is a class and its type must also be a class. Thus its type cannot be of type int which is a built-in type, not a class. Integer is a class representing integers in a class. 2. public String InsertMiddle(String name, String middle) { int blank = name.indexOf(" "); return name.substring(0,blank) + " " + middle + " " + name.substring(blank+1); } 3. A. Dorm B. 1: valid: Keohane 2: error: myName is private and cannot be referred to 3: valid: Nelson: the basketball dorm 4: valid: Blumenhurst: the golf dorm 4. PART A1 public Player (String name, int rank, int grade) { myName = name; myRank = rank; myGrade = grade; } PART A2 // return name of player public String getName() { return myName; } // return rank of player public int getRank() { return myRank; } // return grade of player public int getGrade() { return myGrade; } // increment grade of player by 1, do not change grade for grade 13 players public void incrementGrade() { if (myGrade < 13) myGrade++; } // change rank of player to "rank" public void setRank(int rank) { myRank = rank; } PART B1 public ChessTournament (Scanner input) { myPlayers = new ArrayList(); while (input.hasNext()) { Player temp = new Player(input.next(), input.nextInt(), input.nextInt()); myPlayers.add(temp); } } Part B2 public int NumberPlayersBetween (int minRank, int maxRank) { int count = 0; for (Player temp: myPlayers) { int rank = temp.getRank(); if (rank >= minRank && rank <= maxRank) { count++; } } return count; } PART B3 public String highestPlayerInGrade(int grade) { int maxRank = 0; String maxPlayer = "No Player in this grade."; for (Player temp: myPlayers) { int rank = temp.getRank(); if (temp.getGrade() == grade && rank > maxRank) { maxRank = rank; maxPlayer = temp.getName(); } } return maxPlayer; } PART B4 public ArrayList PlayersWithRankGreater(int rank) { ArrayList PlayersWithRank = new ArrayList(); for (Player temp: myPlayers) { if (temp.getRank() > rank) { PlayersWithRank.add(temp.getName()); } } return PlayersWithRank; }