Issue
public class Menu extends AirPorts{
public static String checkerUK() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
String ukAP = "";
while(valid == false) {
System.out.println("Please enter the code of the UK AirPort ");
ukAP = sc.next();
if(ukAP.equalsIgnoreCase(ukOne)) {
valid = true;
break;
}
if(ukAP.equalsIgnoreCase(ukTwo)) {
valid = true;
}
else {
System.out.println("Please try again");
}
sc.close();
}
return ukAP;
}
}
I'm trying to get checkerUK to return the ukAP within the while loop. The current error I have is,
ukAP cannot be resolved or is not a field
for line, Scanner sc = new Scanner(System.in);
. It seems to be that ukAP
is local to the while loop, and I have tried to put, "return ukAP" within the while loop but then I get an error saying that checkerUK needs to return a String, so it doesn't recognise it.
I have also tried to create a public/global ukAP for the whole class but that doesn't have any affect on the ukAP within the while loop.
I'm using Eclipse and Java 14.
Solution
This works for me.
public static String checkerUK() {
final String ukOne = "LTH";
final String ukTwo = "LGW";
Scanner sc = new Scanner(System.in);
boolean valid = false;
String ukAP = "";
System.out.print("Please enter the code of the UK AirPort: ");
while (valid == false) {
ukAP = sc.nextLine();
switch (ukAP) {
case ukOne:
case ukTwo:
valid = true;
break;
default:
valid = false;
System.out.print("Please try again: ");
}
}
return ukAP;
}
Java supports string switch since Java 7. The values must be constant, though. That's why I declared them as final
.
Never close a Scanner
that wraps System.in
.
Answered By - Abra