例如,当用户键入“ September”,“ SEPTEMBER”,“ september”,“ SepTEMber”或任何其他内容时,只要字母正确,它将是有效的输入。编写此代码的更整洁的方法是什么(我使用“ ||”的部分。)?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Compare {
public static void main(String[] args) {
String s1 = getInput("Enter a month ");
if(s1.equals("February")) {
System.out.println("It's time to go to the Disneyland !");
String s2 = getInput("Enter another month: ");
if(s2.equals("February")) {
System.out.println("You already won a Disneyland ticket! Try another month.");
String s3 = getInput("Enter another month: ");
if(s3.equals("January") ||
s3.equals("March") ||
s3.equals("April") ||
s3.equals("July") ||
s3.equals("May") ||
s3.equals("September") ||
s3.equals("October") ||
s3.equals("November") ||
s3.equals("Aguest") ||
s3.equals("July") ||
s3.equals("December")) {
System.out.println("You will go to Paris");
}else {
String s4 = getInput("Leave your name and phone number. We will call you back. ");
System.out.println("Thanks for visiting! Goodbye !");
}
}
}
}
private static String getInput(String prompt) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
}
最佳答案
您还可以考虑将所有月份都放入一个数组中,并进行简单的比较:
String[] months = {"january", "march", "april", ...};
if (Arrays.asList(months).contains(s3.toLowerCase())
System.out.println("You will go to Paris");
您可以内联构造数组,节省一些糟糕的Java样板。