【问题标题】:Issue assigning a value for each character of input and display the value for input为输入的每个字符分配一个值并显示输入的值
【发布时间】:2015-05-13 16:26:49
【问题描述】:

我正在尝试创建一个接受用户输入的程序,扫描每个子字符串并检查该字符是否与字母表中的位置匹配,如果匹配,我想获得分数字符串中的等效位置以获得分数该字符并显示每个字符的分数和总分。

我在下面的代码中应该已经完成​​了我正在尝试做的每个部分,但是第二个 for 循环存在问题,我找不到解决方案,我认为它可能与里面的子字符串有关循环,但我不确定。

import java.util.*;
import java.io.*;
public class testt
{
    public static void main(String [] args) throws IOException
    {
        String alpha = "abcdefghijklmnopqrstuvwxyz";
        String score = "13321424185131139111144849";
        String result = "";
        int value = 0, total = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter word: ");
        String input = in.nextLine();
        if(input == null || input.length() == 0)
        {
            System.out.println("Enter input.");
            System.exit(0);
        }
        String inputLower = input.replaceAll("[^a-zA-Z ]", "").toLowerCase();
        String inputArray[] = inputLower.split("\\s+");
        for(int i = 0; i < alpha.length(); i++)
            if(inputLower.substring(i, i + 1) == alpha.substring(i, i + 1))
            {
                value = Integer.parseInt(score.substring(i, i + 1));
                if(value == 9)
                    value++;
                result += inputLower.substring(i, i + 1) + " will give you " + value + " point(s)\n";
                total += value;
            }
            else if(i == alpha.length() + 1)
            {
                System.out.println(result + "This word will earn you: " + total);
                System.exit(0);
            }

    }
}

任何建议或提示我都会非常感激,因为我认为我的程序已经基本完成了。

这是我从http://i.imgur.com/ftfcINX.jpg学习的问题

【问题讨论】:

    标签: java string loops if-statement for-loop


    【解决方案1】:

    您的实际代码显示了主要问题,我将说明:

    1. 您正在循环通过alpha.length 并且您有风险获得 进入StringIndexOutOfBoundsException,所以最好检查i 不大于input.length
    2. 您正在使用substring(i,i+1) 获取该位置的字符 i 您可以将其替换为专为此设计的.charAt(i)
    3. 如果给定单词​​中有字符,您将退出应用程序 与 alpha 中对应的不匹配,因此您要退出 不检查输入的所有字符...

    我尝试更正您的代码,结果如下:

        String alpha = "abcdefghijklmnopqrstuvwxyz";
        String score = "13321424185131139111144849";
        String result = "";
        int value = 0, total = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter word: ");
        String input = in.next();
    
    
        for(int i = 0; i < input.length(); i++) {
    
        if( i<alpha.length()) {
            if(input.charAt(i) == alpha.charAt(i))
            {
                value = Integer.parseInt(score.charAt(i)+"");
                if(value == 9)
                    value++;
                result += input.charAt(i) + " will give you " + value + " point(s)\n";
                total += value;
            }
        }
        }
        System.out.println(result + "This word will earn you: " + total);
    

    这是一个Live DEMO,以alcme 作为输入并给出以下结果:

    a will give you 1 point(s)
    c will give you 3 point(s)
    e will give you 1 point(s)
    This word will earn you: 5
    

    【讨论】:

    • 指出他的错误做得很好。我只是重写了他的一些代码,这些代码没有多大帮助
    【解决方案2】:

    由于inputArray 中可能有多个单词,因此您需要两个嵌套循环而不是单个循环。循环应该逐个遍历inputArray,然后在该数组内部遍历字母表并进行评分:

    String alpha = "abcdefghijklmnopqrstuvwxyz";
    //             a b c d e f g h i j k l m n o p q  r s t u v w x y z
    int[] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
    int total = 0;
    for (String word : inputArray) {
         int wordTotal = 0;
         for(int i = 0; i < word.length(); i++) {
             char letter = word.charAt(i);
             int pos = alhpa.indexOf(letter);
             int value = score[pos];
             System.out.println("Letter "+letter+" will earn you: " + value);
             // Increment wordTotal, not total
             wordTotal += value;
         }
         System.out.println("Word "+word+" will earn you: " + wordTotal);
         total += wordTotal;
    }
    System.out.println("Total for all words: " + total);
    

    以下是一些实现说明:

    • 使用整数数组而不是字符数组可以避免将十个“编码”为'9',并帮助您放弃if (value == 9) hack。
    • 与其使用子字符串并在字符串中查找单词,不如使用indexOf 代替char,并使用该索引查找分数数组。

    【讨论】:

      【解决方案3】:

      我想我的两分钱,我有点晚了。 您可以将实际的分数代码放入一个函数中并在循环中调用它

      public class Test {
        public static void main(String[] args) throws IOException {
      
          int total = 0;
      
          Scanner in = new Scanner(System.in);
      
          System.out.print("Enter word: ");
      
          String input = in.nextLine();
      
          // Close the input stream to avoid memory leaks
          in.close();
      
          if (input == null || input.length() == 0) {
              System.out.println("Enter input.");
              System.exit(0);
          }
      
          String inputLower = input.replaceAll("[^a-zA-Z ]", "").toLowerCase();
      
          String inputArray[] = inputLower.split("\\s+");
      
          // Loop through each entered word, I only did this step because you appeared to split up the input even though the Array wasn't actually being used in your original program
          for(String word : inputArray) {
      
              int currentWordTotal = 0;
      
              // Use a method to get the value for each letter in the current word
              for(int i = 0; i < word.length(); i++) {
      
                  currentWordTotal += letterScore(word.charAt(i));
      
              }
      
              // Print out the word total
              System.out.println("Word: " + word + ",  will earn you: " + currentWordTotal + " points.");
      
              // Keep track of all word total in the event that multiple words were entered
              total += currentWordTotal;
      
          }
      
          // Print out the total for all words
          System.out.println("Your Total for the entered Words: " + total);
      
      
      }
      
      private static int letterScore(char letter) {
      
          char[] letters =  {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u', 'v', 'w', 'x', 'y', 'z'};
          int[] scores = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 9, 1, 1, 1, 1, 4, 4, 8 ,4 ,10};
      
          // Here we look through the array of letters, when we find a match we use the index of the character array to get the corresponding value from the score array
          for(int i = 0; i < letters.length; i++) {
      
              if(letters[i] == letter) {
                  return scores[i];
              }
          }
          return 0;
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 2022-01-19
        • 2014-10-21
        • 1970-01-01
        • 2015-12-04
        • 2018-09-30
        • 2021-06-13
        相关资源
        最近更新 更多