Skip Top Navigation Bar

AP Computer Science A FRQ 1 Sentence Analysis

Sentence Analysis

This is a two part question for FRQ #1. Part a is worth 3 points and part b is worth 4 points.

AP CSA Alignment

Unit Alignment Learning Objectives Resources Skills
Unit 1: Using Methods and Objects 1.15.B Develop code to create string objects and determine the result of creating and combining strings. 2.C Write program code involving procedural abstractions.
Unit 2: Selection and Iteration 2.3.A Develop code to represent branching logical processes by using selection statements and determine the result of these processes. 2.A Write program code to implement an algorithm.
2.8.A Develop code to represent iterative processes using for loops and determine the result of these processes.
2.10.A Develop code for standard and original algorithms that involve strings and determine the result of these algorithms.

Write a class SentenceAnalyzer that analyzes a sentence (a String consisting of words separated by single spaces, with no punctuation). The class has the following methods:

  • public static int countWord(String sentence, String word) - to be answered in part a.
  • public static String swapFirstLast(String sentence) - to be answered in part b.

Part a: countWord Method

Write a static method countWord that takes two parameters: a String sentence and a String word. The method returns the number of times word appears in the sentence. Two words will not match if there are case discrepancies.

Example:

  • countWord("java is fun and java is powerful", "java") returns 2
  • countWord("Test test TEST", "test") returns 1

Part b: swapFirstLast Method

Write a static method swapFirstLast that takes a String sentence and returns a new String in which the first and last words have been swapped. Spaces between words must be preserved, and words are separated by a single space. If there is only one word, return the original sentence.

Examples:

  • swapFirstLast("coding is creative") returns "creative is coding"
  • swapFirstLast("hello") returns "hello"