比较用户输入与字符串
问题描述:
我是Java新手,我正在用Greenfoot编写这个简单的程序。 如果我写“h”,程序会说“相同”,现在我想写“i”并得到“相同”,基本上我想在我得到“相同”后忽略“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");
}
}
}
答
只需在调用时给letterh指定新值(当“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))
{
Called.call1();
}
}
if (keyPress2 != null)
{
if(keyPress2.equals(letteri))
{
Called.call2();
}
else
{
System.out.println("Not same");
}
}
}
使用以下代码创建一个新的Class文件“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");
}
}
这里要注意的主要问题是static关键字的用法。
我会试试这个。 – kolozz
等待结果...它解决了问题吗? –
非常感谢!它的工作,我不得不删除System.out.println(“不一样”);从act方法并将其添加到call2()。我还删除了keyPress2并使用了keyPress1。它现在工作,因为我想它的工作!谢谢! – kolozz