-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringFormatter.java
More file actions
84 lines (66 loc) · 2.18 KB
/
StringFormatter.java
File metadata and controls
84 lines (66 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.ArrayList;
/**
* Write a description of class StringFormatter here.
*
* @author Sofie Budman
* Period 5
* @version 2/25
*/
public class StringFormatter
{
public static int totalLetters(ArrayList<String> wordList)
{
int c = 0;
for(String s: wordList){
c += s.length();
}
return c;
}
// must use totalLetters to receive full credit
public static int basicGapWidth(ArrayList<String> wordList, int formattedLen)
{
int length = totalLetters(wordList);
return (formattedLen - length )/ (wordList.size() -1);
}
public static int leftoverSpaces(ArrayList<String> wordList, int formattedLen)
{
int length = totalLetters(wordList);
return (formattedLen - length ) % (wordList.size()-1);
}
// must use basicGapWidth and leftoverSpaces to receive full credit
public static String format(ArrayList<String> wordList, int formattedLen)
{
String out = "";
int extra = leftoverSpaces(wordList, formattedLen);
for(String s: wordList){
out += s;
for(int i = 0; i < basicGapWidth(wordList, formattedLen); i++){
out += " ";
}
if(extra >0){
out += " ";
extra --;
}
}
return out;
}
public static void main(String[] args)
{
ArrayList<String> arr1 = new ArrayList<String>();
String correct1 = "GREEN EGGS AND HAM";
String correct2 = "BEACH BALL";
arr1.add("GREEN");
arr1.add("EGGS");
arr1.add("AND");
arr1.add("HAM");
System.out.println("Test1: The following 2 lines should be the same.");
System.out.println(StringFormatter.format(arr1, 20));
System.out.println(correct1.length());
ArrayList<String> arr2 = new ArrayList<String>();
arr2.add("BEACH");
arr2.add("BALL");
System.out.println("Test2: The following 2 lines should be the same.");
System.out.println(StringFormatter.format(arr2, 20));
System.out.println(correct2);
}
}