THINK FIRST·CODE LATER

← All labs

MyBuilder: how a StringBuilder works inside

Problem

A String cannot be changed; a StringBuilder can, because it keeps its characters in an array with spare room. Write your own small version, MyBuilder, with a char[] buffer (starting capacity 8) and a counter size:

  • MyBuilder(String start);
  • append(String) and append(int) — both return this, so calls can be chained;
  • reverse(), toLowerCase() — change the builder itself and return this;
  • length(), capacity(), charAt(int), substring(int begin, int end), toString();
  • a private ensureCapacity(int needed) that doubles the array until the characters fit.

MyBuilderApp reads the commands add word, number 42, reverse, lower, char 2, part 1 4, show until the end of the input, then prints the final content. For the input

add Hello
show
add World
number 2026
show
char 4
part 5 10
reverse
show
lower

the program prints

Hello (length 5, capacity 8)
HelloWorld2026 (length 14, capacity 16)
Character 4: o
Part 5..10: World
6202dlroWolleH (length 14, capacity 16)
Final: 6202dlrowolleh

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l13-8-data-1.txt

add Hello
show
add World
number 2026
show
char 4
part 5 10
reverse
show
lower
What your program must print for l13-8-data-1.txt
Hello (length 5, capacity 8)
HelloWorld2026 (length 14, capacity 16)
Character 4: o
Part 5..10: World
6202dlroWolleH (length 14, capacity 16)
Final: 6202dlrowolleh

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l13-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l13-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.