英文:
How can I get my code to return the correct variable?
问题
public class Menu extends AirPorts {
public static String checkerUK() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
String ukAP = "";
while (!valid) {
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;
}
}
Please note that I've fixed the issue with the variable scope and indentation in your provided code. Make sure you have the necessary definitions of ukOne
and ukTwo
in the AirPorts
class, and ensure that you import the required classes (AirPorts
and Scanner
) in your code.
英文:
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.
答案1
得分: 0
这对我有效。
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("请输入英国机场代码:");
while (valid == false) {
ukAP = sc.nextLine();
switch (ukAP) {
case ukOne:
case ukTwo:
valid = true;
break;
default:
valid = false;
System.out.print("请重试:");
}
}
return ukAP;
}
自从Java 7起,Java支持[字符串开关][1]。但值必须是常量。这就是为什么我将它们声明为`final`。
永远不要关闭包装了`System.in`的`Scanner`。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论