Avatar of hrodward

hrodward's solution

to Bob in the Java Track

Published at Oct 15 2019 · 0 comments
Instructions
Test suite
Solution

Bob is a lackadaisical teenager. In conversation, his responses are very limited.

Bob answers 'Sure.' if you ask him a question.

He answers 'Whoa, chill out!' if you yell at him.

He answers 'Calm down, I know what I'm doing!' if you yell a question at him.

He says 'Fine. Be that way!' if you address him without actually saying anything.

He answers 'Whatever.' to anything else.

Bob's conversational partner is a purist when it comes to written communication and always follows normal rules regarding sentence punctuation in English.

Tips

Since this exercise has difficulty 5 it doesn't come with any starter implementation. This is so that you get to practice creating classes and methods which is an important part of programming in Java. It does mean that when you first try to run the tests, they won't compile. They will give you an error similar to:

 path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
        ExerciseClassName exerciseClassName = new ExerciseClassName();
        ^
 symbol:   class ExerciseClassName
 location: class ExerciseClassNameTest

This error occurs because the test refers to a class that hasn't been created yet (ExerciseClassName). To resolve the error you need to add a file matching the class name in the error to the src/main/java directory. For example, for the error above you would add a file called ExerciseClassName.java.

When you try to run the tests again you will get slightly different errors. You might get an error similar to:

  constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
        ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
                                              ^
  required: no arguments
  found: String
  reason: actual and formal argument lists differ in length

This error means that you need to add a constructor to your new class. If you don't add a constructor, Java will add a default one for you. This default constructor takes no arguments. So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself. In the example above you could add:

ExerciseClassName(String input) {

}

That should make the error go away, though you might need to add some more code to your constructor to make the test pass!

You might also get an error similar to:

  error: cannot find symbol
        assertEquals(expectedOutput, exerciseClassName.someMethod());
                                                       ^
  symbol:   method someMethod()
  location: variable exerciseClassName of type ExerciseClassName

This error means that you need to add a method called someMethod to your new class. In the example above you would add:

String someMethod() {
  return "";
}

Make sure the return type matches what the test is expecting. You can find out which return type it should have by looking at the type of object it's being compared to in the tests. Or you could set your method to return some random type (e.g. void), and run the tests again. The new error should tell you which type it's expecting.

After having resolved these errors you should be ready to start making the tests pass!

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Source

Inspired by the 'Deaf Grandma' exercise in Chris Pine's Learn to Program tutorial. http://pine.fm/LearnToProgram/?Chapter=06

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

BobTest.java

import org.junit.Test;
import org.junit.Ignore;
import org.junit.Before;

import static org.junit.Assert.*;

public class BobTest {
    private Bob bob;


    @Before
    public void setUp() {
        bob = new Bob();
    }

    @Test
    public void saySomething() {
        assertEquals(
            "Whatever.",
            bob.hey("Tom-ay-to, tom-aaaah-to.")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void shouting() {
        assertEquals(
            "Whoa, chill out!",
            bob.hey("WATCH OUT!")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void shoutingGibberish() {
        assertEquals(
            "Whoa, chill out!",
            bob.hey("FCECDFCAAB")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void askingAQuestion() {
        assertEquals(
            "Sure.",
            bob.hey("Does this cryogenic chamber make me look fat?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void askingANumericQuestion() {
        assertEquals(
            "Sure.",
            bob.hey("You are, what, like 15?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void askingGibberish() {
        assertEquals(
            "Sure.",
            bob.hey("fffbbcbeab?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void talkingForcefully() {
        assertEquals(
            "Whatever.",
            bob.hey("Let's go make out behind the gym!")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void usingAcronymsInRegularSpeech() {
        assertEquals(
            "Whatever.", bob.hey("It's OK if you don't want to go to the DMV.")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void forcefulQuestions() {
        assertEquals(
            "Calm down, I know what I'm doing!", bob.hey("WHAT THE HELL WERE YOU THINKING?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void shoutingNumbers() {
        assertEquals(
            "Whoa, chill out!", bob.hey("1, 2, 3 GO!")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void onlyNumbers() {
        assertEquals(
            "Whatever.", bob.hey("1, 2, 3")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void questionWithOnlyNumbers() {
        assertEquals(
            "Sure.", bob.hey("4?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void shoutingWithSpecialCharacters() {
        assertEquals(
            "Whoa, chill out!", bob.hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void shoutingWithNoExclamationMark() {
        assertEquals(
            "Whoa, chill out!", bob.hey("I HATE THE DMV")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void statementContainingQuestionMark() {
        assertEquals(
            "Whatever.", bob.hey("Ending with ? means a question.")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void nonLettersWithQuestion() {
        assertEquals(
            "Sure.", bob.hey(":) ?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void prattlingOn() {
        assertEquals(
            "Sure.", bob.hey("Wait! Hang on. Are you going to be OK?")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void silence() {
        assertEquals(
            "Fine. Be that way!", bob.hey("")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void prolongedSilence() {
        assertEquals(
            "Fine. Be that way!", bob.hey("          ")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void alternateSilence() {
        assertEquals(
            "Fine. Be that way!", bob.hey("\t\t\t\t\t\t\t\t\t\t")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void multipleLineQuestion() {
        assertEquals(
            "Whatever.",
            bob.hey("\nDoes this cryogenic chamber make me look fat?\nNo.")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void startingWithWhitespace() {
        assertEquals(
            "Whatever.",
            bob.hey("         hmmmmmmm...")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void endingWithWhiteSpace() {
        assertEquals(
            "Sure.",
            bob.hey("Okay if like my  spacebar  quite a bit?   ")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void otherWhiteSpace() {
        assertEquals(
            "Fine. Be that way!",
            bob.hey("\n\r \t")
        );
    }

    @Ignore("Remove to run test")
    @Test
    public void nonQuestionEndingWithWhiteSpace() {
        assertEquals(
            "Whatever.",
            bob.hey("This is a statement ending with whitespace      ")
        );
    }

}
class Bob {

  public String hey(String input) {

    String phrase = removeUnnecessaryCharacters(input);

    if (phrase.isEmpty()) {
      return "Fine. Be that way!";
    }

    int letterCounter = 0;
    int upperCaseCounter = 0;

    for (String letter : phrase.split("")) {
      if (letter.matches("[A-Za-z]")) {
        letterCounter++;
        if (letter.matches("[A-Z]")) {
          upperCaseCounter++;
        }
      }
    }

    boolean isQuestion = phrase.charAt(phrase.length() - 1) == '?';
    boolean isAggressive = upperCaseCounter > 1 && upperCaseCounter == letterCounter;

    if (isQuestion) {
      if (isAggressive) {
        return "Calm down, I know what I'm doing!";
      } else {
        return "Sure.";
      }
    } else if (isAggressive) {
      return "Whoa, chill out!";
    }

    return "Whatever.";
  }

  private String removeUnnecessaryCharacters(String input) {
    return input.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').replace("  ", " ").trim();
  }

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?