Reputation: 861
I am going through previous exam questions and my question is what is the correct way or ways to determine a String length and return it.
If the String is less than 5 characters in length then I can return it the following way:
public static String first5(String s){
if(s.length() < 5)
return s;
}
If the String is greater than 5 characters though, it can be returned in the following way:
public static String first5(String s){
return s.substring(0, 4);
}
What I must note is that when I answered this type of question before in an in class test, my lecturer stressed that I should not really use 'magic numbers'? I am not sure what he actually meant by that though.
Is there a better way to return this type of method at all?
I am still learning Java so please forgive any errors in my syntax.
Many thanks.
Upvotes: 0
Views: 367
Reputation: 1801
Essentially if the requirements ever change, you can easily change the value in one location; thus, it will be changed everywhere it's referenced. You won't have to worry about any fragments of the old requirements floating around in the code. This is generally a good rule to follow with a large chunk of code.
public class solution {
static final int VAR1 = 0;
static final int VAR2 = 4;
static final int VAR3 = 5;
public static String first5(String s){
if(s.length() < VAR3) {
return s;
} else {
return s.substring(VAR1, VAR2);
}
}
}
Of course the variable names will have to be named something meaningful to the class/application itself.
Upvotes: 1
Reputation: 47739
Note that there's no great shame in using an if statement:
String r = null;
if (s.length() < 5) {
r = s;
}
else {
r = s.substring(0,5);
}
return r;
The logic is clearer than if you use ?:
. The advantage of the latter is that it occupies less screen real-estate, so you can get more of a large function onto a screen -- valuable if you have a large function, but counter-productive if not.
Upvotes: 1
Reputation: 335
Is the number 5 is in your question? If not get the number as input argument with the string input.
Upvotes: 0
Reputation: 200206
This should be your method first5
:
public static String first5(String s){
return s.length() < 5? s : s.substring(0, 5);
}
There are no magic numbers here, but maybe the teacher meant the number 5 was a magic number and wanted you to generalize the function:
public static String firstN(String s, int n){
return s.length() < n? s : s.substring(0, n);
}
Upvotes: 3