【问题标题】:Comparing string and text, character by character逐个字符比较字符串和文本
【发布时间】:2019-10-29 10:21:47
【问题描述】:

我正在制作一个打字游戏。当用户输入一个键时,程序应该将它与存储的字符串/数组进行比较。如果它与该索引处的字符匹配,则分数变量应递增。

我正在尝试将输入的文本存储在一个字符串中,然后在将其分解为字符后进行比较。

         text=new JTextField(40);
         String sentence="the quick brown fox jumps over the lazy dog";
         String store=text.getText();
         for (int i = 0; i < store.length(); i++) {
             if(store[i]==sentence.charAt(i)) {        //error
                 score++;
             }
         }

如果输入的键匹配字符,则增加“分数”,否则减少。

【问题讨论】:

  • store 不是数组
  • storesentence 都是字符串。基于sentence.charAt(i),您熟悉如何在指定位置获取单个字符,那么为什么要使用store[i]

标签: java arrays string user-interface


【解决方案1】:

您的store 变量也是字符串而不是数组,因此您必须使用.charAt()

for (int i = 0; i < Math.min(store.length(), sentence.length()); i++) {
    if(store.charAt(i) == sentence.charAt(i)) {
        score++;
    } else {
        score--;
    }
}

您还应该使用Math.min(store.length(), sentence.length()) 来防止IndexOutOfBoundsException

【讨论】:

  • 为什么是score--
  • OP 在问题中写道“如果输入的键与字符匹配,则增加“分数”,否则减少。”
  • 好的。我错过了:)
【解决方案2】:

我同意 Samuel Philipp 关于使用 .charAt(). 的观点,不过我想补充一下。 .charAt() 在给定索引处搜索字符。根据你的水平,我觉得这个方法是你喜欢的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2012-08-02
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多