如果这个或那个与字符串

时间:2018-07-17 12:57:37

标签: java

一个人如何制作if语句来接受用户输入,然后接受我要求他们使用的单词并在大写或小写版本之间进行选择,并且仍然运行同一行代码?

import java.util.Scanner;
//text game practice

public class textGame {

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int goblin;
    int troll;
    int spider;

    System.out.println("Would you like to play as the Mage, Warrior, or Rouge?");
    String line1 = scan.next();

    System.out.println("Okay " + line1 + " what is your name?");
    String name = scan.next();

    if (name.equals("Mage" || "mage")) {
        System.out.println("You are a mage named " + name + " from a small wizardry school in the north.");
    }
    if (name == "Warrior" || "warrior") {
        System.out.println("You are a warrior named " + name + " fresh out of the new cadets at the Gambleton Outpost.");
    }
    if (name == "Rouge" || "rouge") {
        System.out.println("You are a rouge named " + name + " you were trained by petty theives in the streets of Limburg.");
    }    
    else {
        System.out.println("You did not answer the question correctly please try again.");
    } 
  }
}

1 个答案:

答案 0 :(得分:1)

使用equalsIgnoreCase方法:

if (name.equalsIgnoreCase("mage")) {
    System.out.println("You are a mage named " + name + " from a small wizardry school in the north.");
}

在您的情况下,它将无法编译。 代替name.equals("Mage" || "mage")使用:

if (name.equals("mage") || name.equals("Mage")) {
    System.out.println("You are a mage named " + name + " from a small wizardry school in the north.");
}

您不能在||方法内使用equals,但可以将if子句拆分为2个不同的语句。