2012-02-14 3 views
0

여기에 제 코드가 있습니다.출력은 항상 else 문을 인쇄합니다 (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
if ("air".equals(input)||"water".equals(input)|| "steel".equals(input)){ 

문자열 비교

+0

오, 좋아. 고맙습니다. 유명한. –

0

Don't use == ==하지, 동등해야한다. 정적 java.util.Set<String>

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

또는 :

if (valid.contains(input)) { 
+0

감사합니다. 나갔다. –

관련 문제