输出总是打印出else语句

时间:2012-02-14 00:51:10

标签: java

这是我的代码。

import java.util.Scanner;

public class ORR_P02 {
public static void main(String args[]){

    String input;
    char medium1;
    double distance;

    Scanner medium = new Scanner(System.in);//Scanner for user input of the type of medium
    Scanner traveled = new Scanner(System.in);//Scanner for the distance traveled

    System.out.print("Please enter the type of medium (Air, Water, Steel):");
    input = medium.next().toLowerCase();

    //this was to make sure it was changing it to lower case
    System.out.println(input);

    if (input == "air"||input == "water"||input == "steel"){

        //used to get the first character of the input they had to match the switch case
    medium1 = input.charAt(0);

    switch (medium1)
    {
    case 'a':
        System.out.println("Please enter the distance here:");
        break;
    case 'w':
        System.out.println("Please enter the distance here:");
        break;
    case 's':
        System.out.println("Please enter the distance here:");
        break;


    }

    }
    else{
        System.out.println("Incorrect type of medium entered.");
    }
    }
}

我想要做的就是当用户输入内容时;如果它与if语句不匹配,那么它只打印else语句。唯一的问题是它总是打印出else语句,无论如何。

只要输入等于空气,水或钢,我希望它在两者之间运行switch语句。这就是charAt在那里的原因。有关如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:2)

   if ("air".equals(input)||"water".equals(input)|| "steel".equals(input)){ 

Java中的字符串比较应该是等于,而不是==

答案 1 :(得分:0)

Don't use ==

if (input.equals("air") || ...) {

或使用静态java.util.Set<String>

if (valid.contains(input)) {