I need to return the middle 2 characters of a word, favoring the right.
so for example:
- SevenMethods myFuns = new SevenMethods();
-
assertEquals("34", myFuns.middleTwo("12345"));
so far i have:
- public String middleTwo(String arg) {
-
int middle = arg.length() / 2;
-
int middle2 = middle / 2;
-
String middleTwo = "" + arg.charAt(middle2) + "" + arg.charAt(middle);
-
return middleTwo;
I can't figure out how to favor the right.
OK, let's just test your code for a moment.
Say, you call
- String result = middleTwo("12345");
, then the following will happen:
- public String middleTwo("12345") {
-
int middle = "12345".length() / 2; // = 5 / 2 = 2 (as you're using integers)
-
int middle2 = 2 / 2; // = 1
-
String middleTwo = "" + "12345".charAt(1) + "" + "12345".charAt(2); // = "" + 2 + "" + 3
-
return "23";
-
}
That isn't what you want, is it? You want it to return "34".
So, let's have a look at the possible options:
- You give the middleTwo() method a String with an odd number of characters
- You give the middleTwo() method a String with an even number of characters
With option a. (e.g. "12345"), the middle will be
lengthOfTheString / 2 - 0.5 (so, with a String of the length 5, that would be 2) and you will want that and the following character (as Java starts counting at 0).
With option b. (e.g. "123456"), the middle will be
lengthOfTheString / 2 exactly, so in the case of 6 characters, it will be 3. You want character 2 and 3. So, can you find a formula to always get the first of the characters you want? Then you just have to write that and the following character.
Greetings,
Nepomuk