Adi Adi - 2 months ago 11
Java Question

Java Compiler Error: not a statement

Hi I am new to java programming. I want to write a java program that gets the first name and the surname initials of the user. My code is:

public class MyProgram {
public void start() {
String name = getNameFromUser();
char firstNameInitials = getInitials(name);
char surnameInitials = getInitials(name);
printInitials(firstNameInitials, surnameInitials);
}
private String getNameFromUser() {
System.out.print("Please enter your name: ");
String name = Keyboard.readInput();
return name;
}
private char getInitials(String name) {
char firstNameInitials = name.charAt(0);
int indexOfSpace = name.indexOf(" ");
char surnameInitials = name.charAt(indexOfSpace + 1);

return firstNameInitials; surnameInitials;
}

private void printInitials(String firstNameInitials, String surnameInitials){
System.out.print("your initials are: " + firstNameInitials +". " + surnameInitials +".");
}
}


i am getting an error message, i dont know what it means:

Error: not a statement.


The error seems to be at line 18, at the return statement.
I have tried to fix it but have failed. Any suggestions how can I fix this please?

Answer
return firstNameInitials; surnameInitials;

you can not return multiple char like this. Instead use a char array to return

For example you can return like this

private char[] getInitials(String name) {
    char firstNameInitials = name.charAt(0);
    int indexOfSpace = name.indexOf(" ");
    char surnameInitials = name.charAt(indexOfSpace + 1);

    char[] result  = {firstNameInitials, surnameInitials};
    return result;
}

And call it like

char[] a = getInitials(name);
char firstNameInitials = a[0];
char surnameInitials = a[1];
Comments