如何在没有出现“重复”错误的情况下,如何让我的主要if,elseIf和else做同样的事情?

时间:2015-07-05 18:05:26

标签: java

我的主要If语句要求输入。如果它是“二月”,它将进入下一步。我希望这些相同的步骤适用于我的主要elseif,以及他们自己完成后的其他步骤。 我还想将“二月”转换为“allUppercase”或“alllowerCase”以使其不敏感。但是当我写“”(s1.toLowerCase(“february”))“”我写错了 感谢

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Compare {

public static void main(String[] args) {
    String[] months1 = {"january","march","april","may","june","july","augest","september","october","november","december"};
    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: ");
            String[] months = {"january","march","april","may","june","july","augest","september","october","november","december"};               
            if(Arrays.asList(months).contains(s3.toLowerCase())) {
                  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 !" + s4);
            }    
        }
    }else if(Arrays.asList(months1).contains(s1.toLowerCase())){
        System.out.print("Sorry we don't have any specials yet");

    }else{
        System.out.print("Phahaha:))) choose sthg else");
    }

}
            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();
      }

 }

}

3 个答案:

答案 0 :(得分:1)

使用

s1.equalsIgnoreCase("february")

比较你的字符串忽略大小写:

  

equalsIgnoreCase将此String与另一个String进行比较,忽略了大小写。如果两个字符串具有相同的长度并且两个字符串中的相应字符等于忽略大小写,则认为它们是相等的忽略大小写。

无论如何,如果乔恩建议使用java.text.Collator,我会信任他!

答案 1 :(得分:1)

是的确if(s1.toLowerCase("february"))是一个编译错误,因为s1.toLowerCase("february")返回一个字符串而if ()需要一个布尔值。

使用if(s1.equalsIgnoreCase("february"))`来比较你的字符串忽略大小写

答案 2 :(得分:1)

至于你的其他问题,你可以在比较类上创建一个方法,在main方法之外封装你想要每个if语句执行的所有代码,并从每个if语句中调用该方法。