在字符串数组

时间:2015-09-24 11:12:30

标签: java

我无法弄清楚编程逻辑。如何获取字符串数组以随机索引打印asteriks。请注意,3是要在阵列中生成的星号数。

所以输出可以是[a,b *,c *,d,e *,f,g,h]或[a *,b,c,d,e,f,g *,h *] < / p>

public class Generate
    {
      public static void main(String[] args)
      {
        String[] list = {"a","b","c","d","e","f","g","h"};

        for(int i =0; i <list.length; i++)
        {
          System.out.print("   " + list[i]);
          generateAsterisk(list);
        }
        System.out.println();

      }

      public static void generateAsterisk(String[] list)
      {
        for(int i = 0; i < 3; i++)
        {
          int index = (int)(Math.random()*i);

        }
              System.out.print("*");
      }
    }

2 个答案:

答案 0 :(得分:3)

你可以这样做:

import java.util.Random;

public class Generate {

public static void main(String[] args) {
    String[] list = { "a", "b", "c", "d", "e", "f", "g", "h" };

    //do it 3 times or change to as many times you want to add an asteriks
    for (int i = 0; i < 3; i++) {
        addRandomAsteriks(list);
    }

    //print the array
    for (int i = 0; i < list.length; i++) {
        System.out.print("   " + list[i]);
    }
    System.out.println();

}

    public static void addRandomAsteriks(String[] list) {
      Random rand = new Random();
      int randomNumber = rand.nextInt(list.length - 1);
      String string = list[randomNumber]; //get the string at the random index
      if (!string.contains("*")) {
          // add the asteriks
          list[randomNumber] = string.concat("*"); 
      }else {
          //if it had already an asteriks go through the 
          //add-method again until you find one that has no asteriks yet.
          addRandomAsteriks(list);
      }
    }

这是一个比YassinHH的回答更加面向对象的观点。

此解决方案有效且仅使用数组。

答案 1 :(得分:0)

您只能使用所需的星号数量调用generateAsteriks方法一次:

String[] list = {"a","b","c","d","e","f","g","h"};

generateAsterisks(list, 3);
...

并将您的generateAsteriks方法更改为:

public static void generateAsterisks(String[] list, int numAsteriks)
{
    for(int i = 0; i < numAsteriks && i < list.length; i++)
    {
        int index = (int)(Math.random()*list.length);

        //check if already added *
        if(list[index].lastIndexOf('*') != list[index].length()-1) {
            list[index] = list[index] + "*";
        } else {
            //don't count this loop iteration
            i--;
        }
    }
}