I'm practicing Java and I've run into a little odd issue or should I say issues.
When I compile the below code it says java line # :error:
missing return statement.
If I remove the comment where I have return "not valid"
, it compiles.
Now this is where the other issue comes in. When I pass the init_config
and final_config
string that I input as A
and B
, it returns the not valid. But when I pass "A"
and "B"
to other function (other("A", "B")
the specific return which is "C"
is returned/printed.
I am not sure if the the issue lies with my input method. The data I input for my init_config and final_config should be string values, correct? I'm not sure if Scanner is a good string input method. However, if I print the two inputs it works fine so I'm not sure if it is data loss or the string reference is lost when it is passed.
I also tried replacing init_config = in.next()
with init_config = in.nextLine()
but it did not make any difference.
Is it necessary to compile the code with the return "not valid"
at the end of the function or can I bypass this by some method? And how can I pass String data using Scanner
input method without any loss?
Here is my code:
import java.util.Scanner;
public class towerGen
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
String init_config, final_config;
System.out.print("Enter initial configuration: ");
init_config = in.next();
System.out.print("Enter final configuration: ");
final_config = in.next();
System.out.print(other(init_config, final_config));
}
public static String other(String src, String dest)
{
if (src=="A" && dest=="B")
return "C";
if (src=="B" && dest=="A")
return "C";
if (src=="B" && dest=="C")
return "A";
if (src=="C" && dest=="B")
return "A";
if (src=="A" && dest=="C")
return "B";
if (src=="C" && dest=="A")
return "B";
//return "not valid";
}
}