【问题标题】:Assign unique int values to a word in a String then store it into an Array为字符串中的单词分配唯一的 int 值,然后将其存储到数组中
【发布时间】:2021-08-01 06:22:44
【问题描述】:

我正在尝试获取字符串中的唯一单词,然后将其连同它出现的次数一起存储在一个数组中。

我的方法是为if-else 语句中的每个唯一字符串分配一个唯一整数,然后获取这些整数的唯一计数,并从分配了唯一值的字符串中提取任何一个单词,最后获取唯一整数出现的次数。

但是,每当我为 String 分配唯一值时,我都会得到 null

import java.util.Arrays;

public class StringLearning {

    public static void main(String[] args) {
        
    final   String text = "Win Win Win Win Draw Draw Loss Loss";

    int[] numbers = null;
    
    
 if(text.equals("Win")) {
     numbers= new int[1];
    
 }else if(text.equals("Draw")){
     numbers = new int  [2];
    
 }else if(text.equals("Loss")) {
     numbers = new int [3];
     
 } 
 System.out.println(Arrays.toString(numbers));
    

        }
        
    }

预期输出:

{1, 1, 1, 1, 2, 2, 3, 3}

编辑: 这如何在一般意义上实施?这样,我不知道字符串中有“Win, Loss, Draw”,但我想为任何给定的唯一单词分配一个唯一整数?

【问题讨论】:

  • "numbers= new int[1];" - 这并不像您认为的那样。我建议阅读有关基本类型的教程以及有关数组的教程。两者都包含在this tutorial by Oracle
  • 这太糟糕了,我不认为它算作代码的“尝试”。请向您的教练寻求帮助,他们需要知道您正在为此苦苦挣扎。
  • @markspace 过去 2 周我一直在自学,所以我对 java 词典比较陌生。
  • 我认为你需要一种更有条理的方法,也许可以找一个在线课程或社区大学之类的东西,你上面的东西根本不起作用。
  • @Stackbeans – 如果目前没有您可以询问的讲师,那么您应该寻找一位!抱歉,代码确实不是解决所描述问题的尝试,绝不是!!

标签: java arrays string integer


【解决方案1】:

你的代码有很多问题。

首先,你必须得到字符串的每个单词,所以你需要将split它放入数组中。

其次,您需要创建一个数组,并将整数放入其中。 (您所做的是为每个数字创建新数组)

我试图解决这些问题。希望你能理解我的代码。 (我只修复了你的代码,并没有使其通用)

 String[] arr = text.split(" ");
 int[] numbers = new int[arr.length];
    
 for (int i=0;i<arr.length;i++){
    
    if(arr[i].equals("Win")) {
         numbers[i] = 1;
    
     }else if(arr[i].equals("Draw")){
         numbers[i] = 2;
    
     }else if(arr[i].equals("Loss")) {
         numbers[i] = 3;
      }
   }
     

【讨论】:

  • 不鼓励使用纯代码的答案。我们宁愿解释问题(s9 以及我们的解决方案如何解决它。
  • @Turing85 – 更不用说该解决方案做出了(很可能是无效的)假设,即唯一有效的词是“Win”、“Draw”和“Loss”……
  • Welp,这个问题的最后一次编辑使这个答案无效......
【解决方案2】:

在创建数组对象时,括号中的数字new int[1]你声明了数组的长度。我建议为此使用 HashMap 。代码示例如下:

public class StringLearning {

    public static void main(String[] args) {

        final String text = "Win Win Win Win Draw Draw Loss Loss";

        HashMap<String, Integer> counts = new HashMap<String, Integer>();

        for (String word : text.split(" ")) { // loops through each word of the string
            // text.split(" ") returns an array, with all the parts of the string between your regexes
            // if current word is not already in the map, add it to the map.

            if (!counts.containsKey(word)) counts.put(word, 0);

            counts.put(word, counts.get(word) + 1); // adds one to the count of the current word
        }
        // lambda expression
        counts.forEach((string, integer) -> System.out.printf("amount of \"%s\": %d\n", string, integer));
    }
}

输出:

amount of "Draw": 2
amount of "Loss": 2
amount of "Win": 4

编辑(响应 tQuadrat): 我编辑了这篇文章以保持一切干净和可读。

public class StringLearning {
    public static void main(String[] args) {

        final String text = "Win Win Win Win Draw Draw Loss Loss";

        HashMap<String, Integer> counts = new HashMap<String, Integer>();

        for (String word : text.split(" ")) { // loops through each word of the string
            // text.split(" ") returns an array, with all the parts of the string between your regexes
            // if current word is not already in the map, add it to the map.
            if (!counts.containsKey(word))
                counts.put(word, counts.size() + 1); // index of the word (+ 1 because your expected output was 1-indexed)

        }
        for (String word : text.split(" ")) {
            System.out.print(counts.get(word) + " ");
        }
    }
}

输出:

1 1 1 1 2 2 3 3 

【讨论】:

  • 你不应该计算单词,你应该用代表它的唯一数字替换每个单词。
  • @tquadrat 我不常来这里,我不知道你是否能看到我的编辑,所以我告诉你我修改了代码以作为一个合适的解决方案
【解决方案3】:

让我们试试这个方法:

  1. 获取字符串中的单词数:var words = text.split( " " ); 这假设单词仅由空格分隔。

  2. 为这些词创建注册表:Map&lt;String,Integer&gt; registry = new HashMap&lt;&gt;();

  3. 创建结果数组:var result = new int [words.length];

  4. 现在遍历单词并检查您是否已经看过该单词:

    for( var i = 0; i < words.length; ++i )
    {
        result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
    }
    
  5. 最后,打印结果:System.out.println( Arrays.toString( result ) );——尽管这将使用[…] 而不是{…}

registry.computeIfAbsent( words [i], $ -&gt; registry.size() + 1 ); 为每个看不见的单词在注册表中添加一个新条目,并将注册表的大小加上一作为该单词的唯一编号。对于已知单词,它返回之前分配的数字。

这适用于text 中的任何单词集。

所以完整的东西可能是这样的:

public final class StringLearning 
{
  public static final void main( final String... args ) 
  {
    final var text = "Win Win Win Win Draw Draw Loss Loss"; // … or any other text
    final var words = text.split( " " );
    final Map<String,Integer> registry = new HashMap<>();
    final var result = new int [words.length];
    for( var i = 0; i < words.length; ++i )
    {
      result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
    }
    System.out.println( Arrays.toString( result ) );
  }
}

【讨论】:

    【解决方案4】:

    维护 map 中字符串的每个单词的唯一值,然后在分配数组时获取唯一值。

    String text = "Win Win Loss Draw Hello";
    String[] split = text.split(" ");
    
    // To maintain unique value for each word of input string 
    Map<String, Integer> = new HashMap<>();
    int counter = 0;
    for(String ele:split)
      if(!map.containsKey(ele))
        map.put(ele, ++counter)
     
    // Getting unique value for each word and assigining in array
    int[] array=new int[split.length];
    for(int i=0; i<split.length;i++)
      array[i] = map.get(split[i]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多