Savage99 Savage99 - 6 months ago 10
Java Question

I need to fix this simple code to have a return value

I have had to change to a return value instead of printing the return values. 1 for odd number of letters in the name, 2 for even letters.

I honestly can't even think right now...my eyes are sideways...can someone help please.

public class new1
{

public static void main(String[] arg)
{

String name = "Jennifer";
{
int count = 0;
for (int i=0; i <+name.length(); i++)
count++;
if (count%2==0)
return 1;
else
return 2;

}
}


}

When I first tried this

public static int main(String[]args)


but eclipse said I was a moron!!!

help

String name = "Jennifer";
{
int count = 0;
for (int i=0; i <+name.length(); i++)
count++;
if (count%2==0)
system.out.println("1");
else
system.out.println("2");

}


And he said I needed a return value and a proper method header

Answer

I am not sure exactly what you are trying to achieve by returning from the main function but if you are trying to do a print you could simply write:

String name = "Jennifer";
System.out.println((name.length() % 2 == 0) ? 0 : 1);

If you really want it to be a return then call a separate function:

public static void main(String[] args) 
{
    String name = "Jennifer";
    System.out.println(letterCounter(name));
}
public static int letterCounter(String phrase)
{
    return (phrase.length() % 2 == 0) ? 0 : 1;
}   
Comments