2013-10-12 2 views
1

저는 Java에서 새로운데,이 간단한 프로그램을 Greenfoot에 씁니다. "h"라고 쓰면 "same"이라고 쓰여지고 "i"라고 쓰고 싶을 때 "same"을 얻은 후에 기본적으로 "h"를 무시하고 싶습니다. 나는 이것이 어떻게 행해졌는지 잘 모르겠습니다.사용자 입력을 문자열과 비교하십시오.

public void act() 
{ 

    String letterh = "h"; 
    String letteri = "i"; 
    String keyPress1 = Greenfoot.getKey(); 
    String keyPress2 = Greenfoot.getKey(); 
    if (keyPress1 != null) 
    { 
     if(keyPress1.equals(letterh)) 
     { 
      System.out.println("Same"); 

     } 
     else 
     { 
      System.out.println("Not same"); 
     } 
    } 

    if (keyPress2 != null) 
    { 
     if(keyPress2.equals(letteri)) 
     { 
      System.out.println("Same"); 
     } 
     else 
     { 
      System.out.println("Not same"); 
     }   
    } 
} 

답변

0

("h"가 적어도 한 번 작성 될 때) 호출 될 때 letterh에 새로운 값을 지정하십시오.

public void act() 
{ 

    String letterh = "h"; 
    String letteri = "i"; 
    String keyPress1 = Greenfoot.getKey(); 
    String keyPress2 = Greenfoot.getKey(); 
    if (keyPress1 != null) 
    { 
     if(keyPress1.equals(letterh)) 
     { 
      Called.call1(); 

     } 

    } 

    if (keyPress2 != null) 
    { 
     if(keyPress2.equals(letteri)) 
     { 
      Called.call2(); 
     } 
     else 
     { 
      System.out.println("Not same"); 
     }  

    } 
} 

다음 코드로 "Called.java"라는 새 클래스 파일을 만듭니다.

public class Called { 
static String count="one"; //observe this static string usage 
static void call1() 
{ 
    if(count.equals("one")) 
    { 
     System.out.println("Same"); 
     count="somestring"; //call1() if condition will fail with this string not equal to "one" 

    } 
    else 
    { 
    System.out.println("Not Same"); 
    } 
} 
static void call2() 
{ 

     System.out.println("Same"); 
} 

} 

중요한 것은 정적 키워드 사용입니다.

+0

나는 이것을 시도 할 것이다. – kolozz

+0

결과를 기다리는 중 ... 문제가 해결 되었습니까 ?? –

+0

정말 고마워요! 그것은 효과가 있었고, System.out.println ("동일하지 않음")을 제거해야했습니다; act 메소드에서 호출하여 call2()에 추가하십시오. 또한 keyPress2를 제거하고 keyPress1을 사용했습니다. 내가 일하기를 원했던 것처럼 지금은 효과가 있습니다! 감사! – kolozz