【发布时间】:2009-04-02 22:25:31
【问题描述】:
我正在尝试从终端读取输入。为此,我使用了 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",值=['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"));
}
}
同样的事情仍在发生。我一定是误解了哈希表。想到哪里出了问题?
【问题讨论】:
-
由于您的问题是在哈希表中放置和获取条目,因此请发布该代码。代码提供的相关性不清楚。