如何将数组转换为不带逗号/括号的String格式,并将括号添加为值

时间:2015-12-05 19:48:37

标签: java arrays string

我想获取我生成的随机值数组,并在相同数字的最长运行之外用括号打印上述数组。 例如,如果数组是[0,1,1,1,2,4,7,4],我想收到0(111)2474作为输出。

到目前为止,这是我的代码。

import java.util.Random;
import java.util.Arrays;

/**
 * Write a description of class ArrayRunner1 here.
 * 
 * @author Ibrahim Khan
 * @version (a version number or a date)
 */
public class ArrayRunner1 {

    /**
     * This method will generate my random numbers for my array. 
     * @param min minimum random value wanted
     * @param max maximum random value wanted
     * @return randomNum a random number between 1 and 6 inclusive
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static void main(String[] args) {
        System.out.println("\f");


        //Part 1 - Generate a random array of length 40 with random 1-6 inclusive
        int[] array1 = new int[40];
        for (int i = 0; i < array1.length; i++) {
            array1[i] = randInt(1, 6);
        }
        System.out.println(Arrays.toString(array1));

        //Counts and RETURN: reports how many times each number is present
        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] == 1) {
                counter1++;
            }
            if (array1[i] == 2) {
                counter2++;
            }
            if (array1[i] == 3) {
                counter3++;
            }
            if (array1[i] == 4) {
                counter4++;
            }
            if (array1[i] == 5) {
                counter5++;
            }
            if (array1[i] == 6) {
                counter6++;
            }
        }

        System.out.println("There are " + counter1 + " ones.");
        System.out.println("There are " + counter2 + " twos.");
        System.out.println("There are " + counter3 + " threes.");
        System.out.println("There are " + counter4 + " fours.");
        System.out.println("There are " + counter5 + " fives.");
        System.out.println("There are " + counter6 + " sixes.");

        //Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.   
        //RETURN: The repeated number and the length of the run is then printed
        int counter = 1;
        int runMax = 1;
        int runMin = 0;
        int variableNum = 0;
        int startCounter = 0;
        int endCounter = 0;

        for (int i = 0; i < array1.length - 1; i++) {

            if (array1[i] == array1[i + 1]) {
                counter++;

                if (counter >= runMax {
                    runMax = counter;
                    runMin = i - counter + 1;
                    variableNum = array1[i];
                    startCounter = i - counter + 2;
                    endCounter = i + counter - 1;
                }
                } else {
                    counter = 1;

                }


            }
            System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
            System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);




            //Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one. 
        }
    }

3 个答案:

答案 0 :(得分:0)

试试这段代码:

import java.util.Arrays;
import java.util.Random;

public class Snippet {
    /**
     * This method will generate my random numbers for my array.
     * 
     * @param min
     *            minimum random value wanted
     * @param max
     *            maximum random value wanted
     * @return randomNum a random number between 1 and 6 inclusive
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static void main(String[] args) {
        System.out.println("\f");

        // Part 1 - Generate a random array of length 40 with random 1-6
        // inclusive
        int[] array1 = new int[40];
        for (int i = 0; i < array1.length; i++) {
            array1[i] = randInt(1, 6);
        }
        System.out.println(Arrays.toString(array1));

        // Counts and RETURN: reports how many times each number is present
        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] == 1) {
                counter1++;
            }
            if (array1[i] == 2) {
                counter2++;
            }
            if (array1[i] == 3) {
                counter3++;
            }
            if (array1[i] == 4) {
                counter4++;
            }
            if (array1[i] == 5) {
                counter5++;
            }
            if (array1[i] == 6) {
                counter6++;
            }
        }

        System.out.println("There are " + counter1 + " ones.");
        System.out.println("There are " + counter2 + " twos.");
        System.out.println("There are " + counter3 + " threes.");
        System.out.println("There are " + counter4 + " fours.");
        System.out.println("There are " + counter5 + " fives.");
        System.out.println("There are " + counter6 + " sixes.");

        // Counts the longest run of the same number. A run continues only when
        // consecutive numbers have the same value.
        // RETURN: The repeated number and the length of the run is then printed
        int counter = 1;
        int runMax = 0;
        int runMin = 0;
        int variableNum = 0;
        int startCounter = 0;
        int endCounter = 0;

        for (int i = 0; i < array1.length - 1; i++) {

            if (array1[i] == array1[i + 1]) {
                counter++;

                if (counter >= runMax) {
                    runMax = counter;
                    startCounter = i - counter +2;
                    // runMin = i-counter+1;
                    variableNum = array1[i];
                    endCounter = i+1;
                }
            } else {
                counter = 1;

            }

        }
        System.out.println("The longest run is " + runMax
                + " times and the number is " + variableNum + ". ");
        System.out.println("The run starts at " + startCounter
                + " and ends at " + endCounter);

        for (int i = 0; i < array1.length; i++) {
            if (i==startCounter) {
                System.out.print("(");
            }
            System.out.print(array1[i]);
            if (i==endCounter) {
                System.out.print(")");
            }
        }
        System.out.println();

        // Prints the array with parentheses outside the longest run, if there
        // is more than one max run, use the last one.
    }
}

答案 1 :(得分:0)

好。我想我有这个。第一个答案很接近,但如果您运行该程序几次,就会发现问题。在上面的代码中有一个逻辑错误,但我有一个解决方法。我想你是如何得到endCounter的。这似乎很奇怪。但据我所知,我得到了该计划。试试吧。我已经多次运行它似乎一致。

import java.util.Random; import java.util.Arrays;

/ **  *在这里写一个ArrayRunner1类的描述。  *  * @author Ibrahim Khan  * @version(版本号或日期)  * / 公共类ArrayRunner1 {

/**
 * This method will generate my random numbers for my array. 
 * @param min minimum random value wanted
 * @param max maximum random value wanted
 * @return randomNum a random number between 1 and 6 inclusive
 */
public static int randInt(int min, int max) {
    Random rand = new Random();
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

public static void main(String[] args) {
    System.out.println("\f");


    //Part 1 - Generate a random array of length 40 with random 1-6 inclusive
    int[] array1 = new int[40];
    for (int i = 0; i < array1.length; i++) {
        array1[i] = randInt(1, 6);
    }
    System.out.println(Arrays.toString(array1));

    //Counts and RETURN: reports how many times each number is present
    int counter1 = 0;
    int counter2 = 0;
    int counter3 = 0;
    int counter4 = 0;
    int counter5 = 0;
    int counter6 = 0;
    for (int i = 0; i < array1.length; i++) {
        if (array1[i] == 1) {
            counter1++;
        }
        if (array1[i] == 2) {
            counter2++;
        }
        if (array1[i] == 3) {
            counter3++;
        }
        if (array1[i] == 4) {
            counter4++;
        }
        if (array1[i] == 5) {
            counter5++;
        }
        if (array1[i] == 6) {
            counter6++;
        }
    }

    System.out.println("There are " + counter1 + " ones.");
    System.out.println("There are " + counter2 + " twos.");
    System.out.println("There are " + counter3 + " threes.");
    System.out.println("There are " + counter4 + " fours.");
    System.out.println("There are " + counter5 + " fives.");
    System.out.println("There are " + counter6 + " sixes.");

    //Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.   
    //RETURN: The repeated number and the length of the run is then printed
    int counter = 1;
    int runMax = 1;
    int runMin = 0;
    int variableNum = 0;
    int startCounter = 0;
    int endCounter = 0;

    for (int i = 0; i < array1.length - 1; i++) {

        if (array1[i] == array1[i + 1]) {
            counter++;

            if (counter >= runMax ){

                runMax = counter;
                runMin = i - counter ;// was plus one I cahnged this.
                variableNum = array1[i];
                startCounter = i - counter + 2;
                endCounter = i + counter -1;
            }
            } else {
                counter = 1;

            }


        }
        System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
        System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);




        //Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one. 
        String output = "";// added this
        for(int x = 0; x < array1.length; x++)
        {
              if( x == startCounter)
              {
                    output += "("+array1[x];
              }
              else if( x == startCounter + runMax )
              {
                    else if( x == startCounter + runMax )
              {
                    if(x == array1.length-1)
                    {
                          output += ")";
                    }
                    else
                    {
                          output += ")"+array1[x];
                    }
              }
              else
              {
                    output += array1[x];
              }
        }
        System.out.print("\n"+output);
       }
}

答案 2 :(得分:0)

这是一个更短,更通用的解决方案。此方法采用任意数组,并在最长的数字周围打印括号。如果有两个相同长度的跑步,它会围绕第一个打印。

public String makeString(int[] ints) {
  if (ints.length == 0) return ""; // Quit early if there's nothing to do.

  // Initialize variables.
  int lastNumber = ints[0];
  // We keep track of the all time best run. Defaults to first int found.
  int bestStart = 0;
  int bestRun = 1;
  // ... as well as the current run.
  int currentStart = 0;
  int currentRun = 1;
  String s = ""+ints[0];

  // Starting from the second int, we check if the current run is continuing.
  for (int i = 1; i < ints.length; i++) {
    int current = ints[i];
    // If the current run continues, we update currentStart/currentRun, else we reset it.
    if (current == lastNumber) {
      currentRun++;
    } else {
      currentStart = i;
      currentRun = 1;
    }

    // Now we check if the currentRun is better than the best.
    // If so, we update bestStart/bestRun.
    if (currentRun > bestRun) {
      bestStart = currentStart;
      bestRun = currentRun;
    }

    lastNumber = current;
    s += current;
  }

  // Now that we've found it, we insert parenthesis aaaaaaand we're done!
  return s.substring(0, bestStart)
      +"("+s.substring(bestStart, bestStart+bestRun)+")"
      +s.substring(bestStart+bestRun);
}