我正在尝试从终端读取输入。为此,我使用了 BufferedReader。这是我的代码。
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] args;
do {
System.out.println(stateManager.currentState().toString());
System.out.print("> ");
args = reader.readLine().split(" ");
// user inputs "Hello World"
} while (args[0].equals(""));
在我的代码的其他地方,我有一个HashTable
键和值都是字符串的地方。这是问题所在:
如果我想从我HashTable
用来在其中查找的键HashTable
是 args 元素之一的地方获取一个值。这些参数很奇怪。如果用户输入两个参数(第一个是命令,第二个是用户想要查找的)我找不到匹配项。
例如,如果 HashTable 包含以下值:
[ {"Hello":"World"}, {"One":"1"}, {"Two":"2"} ]
用户输入:
get Hello
我的代码不返回"World"
。
所以我使用调试器(使用 Eclipse)来查看args
. 我发现args[1]
包含"Hello"
但里面args[1]
有一个名为的字段value
,其值为['g','e','t',' ','H','e','l','l','o']
。
也是如此args[0]
。它包含"get"
但该字段value
包含['g','e','t',' ','H','e','l','l','o']
!
我勒个去!!!
但是,如果我检查我的HashTable
,无论键在哪里"Hello"
, value= ['H','e','l','l','o']
。
有任何想法吗?
非常感谢你。
编辑:
这是代码示例。同样的事情仍在发生。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class InputTest
{
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new InputStreamReader( System.in));
Hashtable<String, String> EngToSpa = new Hashtable<String, String>();
// Adding some elements to the Eng-Spa dictionary
EngToSpa.put("Hello", "Hola");
EngToSpa.put("Science", "Ciencia");
EngToSpa.put("Red", "Rojo");
// Reads input. We are interested in everything after the first argument
do
{
System.out.print("> ");
try
{
args = reader.readLine().trim().split("\\s");
} catch (IOException e)
{
e.printStackTrace();
}
} while (args[0].equals("") || args.length < 2);
// ^ We don't want empty input or less than 2 args.
// Lets go get something in the dictionary
System.out.println("Testing arguments");
if (!EngToSpa.contains(args[1]))
System.out.println("Word not found!");
else
System.out.println(EngToSpa.get(args[1]));
// Now we are testing the word "Hello" directly
System.out.println("Testing 'Hello'");
if (!EngToSpa.contains("Hello"))
System.out.println("Word not found!");
else
System.out.println(EngToSpa.get("Hello"));
}
}
同样的事情仍在发生。我一定是误解了哈希表。想法哪里出了问题?