TurkuBasicOOPinJava / Week 2: Methods, strings and lists /10b. Middle character or nothing
KaiquanMah's picture
Create 10b. Middle character or nothing
e7d25c4 verified
raw
history blame
1.92 kB
Write the method
char middleChar(String str)
...which returns the middle character of the string.
However, if the string contains an even number of characters (i.e. there is no middle character),
the method returns an empty line (i.e. a minus sign).
An example of a method call:
public static void main(String[] args) {
System.out.println(middleChar("abcde"));
System.out.println(middleChar("123"));
System.out.println(middleChar("wxyz"));
}
Program outputs:
c
2
-
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
// String - elements have dtype String
// [] means an array containing elements of the SAME TYPE
// s = string variable
String[] s = "first second third fourth donald test alphabet hello programming choochooo".split(" ");
// from string 's'
// iterate over every sub-string 'pa'
for (String pa : s) {
System.out.println("Testing with parameter " + pa);
System.out.println("Middle character: " + middleChar(pa));
System.out.println("");
}
}
//ADD
public static char middleChar(String str) {
int length = str.length();
if (length % 2 == 0) {
return '-';
} else {
return str.charAt(length / 2);
}
}
}
Testing with parameter first
Middle character: r
Testing with parameter second
Middle character: -
Testing with parameter third
Middle character: i
Testing with parameter fourth
Middle character: -
Testing with parameter donald
Middle character: -
Testing with parameter test
Middle character: -
Testing with parameter alphabet
Middle character: -
Testing with parameter hello
Middle character: l
Testing with parameter programming
Middle character: a
Testing with parameter choochooo
Middle character: c