如何阻止人们在我的代码中按 return

How can I stop people from pressing return in my code

你好基本上写了这段代码,它将哈希映射存储到外部文本文件中所以当用户输入写入时,他们在写入后输入的第一个值(索引 1),第二个值在索引(2),分别存储为键和值。问题是这一切都必须在一行上,如果用户在输入 "write" 后按 return,系统就会崩溃。那么我怎样才能让它不允许用户在输入键和值之前按 return 呢?

这是我的代码,

if (input.contains("write")) {
    String key = input.get(1);
    String value = "";
    for(int i=2; i<input.size(); i++) {
        value = value + " " + input.get(i);
    }
    instruct.mapWrite(key, value);
}

我使用扫描仪 class 获取输入,然后使用以下方法将字符串拆分为数组。这就是我如何将输入存储到 HashMap 中。

public ArrayList<String> getInput() 
    {
        System.out.print("> ");                // print prompt
        String inputLine = reader.nextLine().trim().toLowerCase();

        String[] wordArray = inputLine.split(" ");  // split at spaces

        // add words from array into ArrayList
        ArrayList<String> words = new ArrayList<String>();
        for(String word : wordArray) {
            words.add(word);
        }
        return words;
    }

您无法在此级别阻止它。

但是

  • 告诉用户您的期望,而不是愚蠢的提示,
  • 检查令牌数量(if(wordArray.length < 3)),打印错误消息并再次询问。