compare user input with a string

user2828007

I'm new at Java, I'm writing this simple program in Greenfoot. If I write "h" the program says "same", now after that I want to write "i" and get "same" too, basically I want to ignore "h" after I get "same" for it. I'm not sure how this is done.

    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");
        }           
    }
}
jhon vu

Just assign new value to letterh when invoked(when "h" is written atleast once).

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

    }
}

Create a new Class file "Called.java" with the following code.

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

}

The Main thing to note here is The static keyword usage.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related