about | help | code help+videos | done | prefs |
public String first3Letters(String str)
public String first3Letters(String str) { String s = str.substring(0,3); return s; }But suppose the input parameter has FEWER than 3 letters. For example: "AB" or "A". When you run the program with these inputs, it will "blow up" when it tries to execute the line: String s = str.substring(0,3); because the 2nd parameter 3 violates the rule that both parameters have to be in the range(0,len). The way to solve this problem is use an if statement that will check whether the string is long enough to use in the substring statement. public String first3Letters(String str) { int len = str.length(); if (len >= 3) { String s = str.substring(0,3); } return s; // ERROR: Can't find s ! } Notice the ERROR: s has now become a local variable in the body of the if statement. You have to declare it outside the curly brackets so that the return statement can see it: public String first3Letters(String str) { String s = ""; int len = str.length(); if (len >= 3) { s = str.substring(0,3); } return s; }Now if the string is shorter than 3 letters, the method will return the empty string. However, the specs for the method don't tell us what to do in this case. Here is a new spec: public String first3Letters(String str) Given a String, return ONLY its First 3 letters. If the string has fewer than 3 letters, just return the string itself. This is easy to implement. Simply initialize s with str rather than the empty string (""). public String first3Letters(String str) { String s = str; int len = str.length(); if (len >= 3) { s = str.substring(0,3); } return s; } first3Letters("ab") → "ab" first3Letters("1") → "1" first3Letters("abcd") → "abc" ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 1
Copyright Nick Parlante 2017 - privacy