Java:方法接受一个字符串并构造一个程序,该程序使用for循环输出相同的字符串

时间:2014-06-30 15:06:17

标签: java arrays string arraylist

这是一个实验。我的朋友正试图掌握java并编写文本输出,如下例所示。如果我能提供一个可以生成它们的程序,我想测试自己。

对于String,程序应该对每个字符进行计数,并保存它出现的频率和索引,然后为每个字符生成一个if子句,如下所示:

我想放入,例如“1234123412341234” 得到像

这样的东西
public class ClauseText {
public static void main(String[] args) {
    for(int i = 0; i < 16; i++) {
        if (i == 0 || i == 4 || i == 8 || i == 12) {
            System.out.print("a");
        }
        if (i == 1 || i == 5 || i == 9 || i == 13) {
            System.out.print("b");
        }
        if (i == 2 || i == 6 || i == 10 || i == 14) {
            System.out.print("c");
        }
        if (i == 3 || i == 7 || i == 11 || i == 15) {
            System.out.print("d");
        }
    }
}
}

到目前为止,我想出的是以下内容。我将输入String转换为char数组并遍历数组。我维护了三个数组列表,一个用于字符,一个用于发生频率,一个用于保存包含字符出现位置的索引位置的整数ArrayList。

为了简单起见,我决定使所有ArrayLists的大小为128,并将每个字符放入索引等于其各自的ASCII值。

但它似乎不起作用,这是一个简单的Indexoutofboundsexception,但是,我不知道出了什么问题。这里:

输出只是这么远,然后它崩溃了:

public class ClauseText {
public static void main(String[] args) {
    for(int i = 0; i < 6; i++) {
        if (i == 0 || i == 3) {
            System.out.print("a");
        }
        if (i == 1 || i == 4) {
            System.out.print("b");
        }
        if (i == 2 || i == 5

该计划是:

import java.util.ArrayList;

public class StringToProgram {

public static void main(String[] args) {
    // define and create program
    String className = "ClauseText";
    String program = makeProgram("abcabc", className);
}

public static String makeProgram(String myWord, String className) {
    String program = "public class " + className + " {\n";
    program += "    public static void main(String[] args) {\n";
    program += "        for(int i = 0; i < " + myWord.length()
            + "; i++) {\n";
    char[] myWordChar = myWord.toCharArray();

    // For each character, we have to save the index where it occurs and how
    // often. We want to hash it into the ArrayLists by ASCII value.
    ArrayList<Character> characters = new ArrayList<Character>();
    ArrayList<ArrayList<Integer>> indices = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> amounts = new ArrayList<Integer>();

    // Initialize three lists with the size of the ASCII table
    for (int i = 0; i < 128; i++) {
        characters.add(null);
        indices.add(new ArrayList<Integer>());
        amounts.add(0);
    }

    // Now we iterate through each occurrence. We use the ASCII code to hash
    // and find specific letters.
    for (int i = 0; i < myWordChar.length; i++) {

        int index = (int) myWordChar[i]; // the hash value of the char

        if (amounts.get(index).equals(0)) {
            // create new entries and append them to the
            // given index of the lists
            characters.add(index, myWordChar[i]);
            indices.add(index, new ArrayList<Integer>());
            indices.get(index).add((Integer) i);
            amounts.add(index, 1);
        } else {
            // there is already an entry. modify it.
            amounts.add(index, amounts.get(index) + 1); // ++
            indices.get(index).add((Integer) i);
        }
    }

    // Now, we iterate through the occurrences list. First, we check for
    // each index if an object is saved there.
    for (int i = 0; i < amounts.size(); i++) {
        if (amounts.get(i) > 0) {
            // When this is the case, we append an if clause.
            program += "            if (i == ";
            for (int j = 0; j < amounts.get(i); j++) {
                // The amount of options in the if clause depends on how
                // often the character occurred in the string.
                program += indices.get(i).get(j);
                if (j + 1 < amounts.get(i)) {
                    // we still have to append an option
                    program += " || i == ";
                }
            }
            program += ") {\n";
            program += "                System.out.print(\""
                    + characters.get(i) + "\");\n";
            program += "            }\n";
        }
    }
    program += "        }\n";
    program += "    }\n";
    program += "}";

    System.out.println(program);
    return program;
}

}

错误如下:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at StringToProgram.makeProgram(StringToProgram.java:60)
at StringToProgram.main(StringToProgram.java:8)

2 个答案:

答案 0 :(得分:0)

您会收到此异常,因为在某些情况下,此行中返回的列表不包含元素。

您需要以下代码:

List<Integer> numbers = indices.get(i);
for (Integer number : numbers) {
    program += number;
    program += " || i == ";
}

而不是你的代码:

program += indices.get(i).get(j);
if (j + 1 < amounts.get(i)) {
   // we still have to append an option
   program += " || i == ";
}

答案 1 :(得分:0)

也许你应该开始更简单:

public class StringToProgram {

    public static void main(String[] args) {
        // define and create program
        String className = "ClauseText";
        String program = makeProgram("a\nbca\rbc", className);
    }

    public static String makeProgram(String myWord, String className) {
        myWord = myWord.replace("\\", "\\\\");
        myWord = myWord.replace("\t", "\\t");
        myWord = myWord.replace("\b", "\\b");
        myWord = myWord.replace("\n", "\\n");
        myWord = myWord.replace("\r", "\\r");
        myWord = myWord.replace("\f", "\\f");
        myWord = myWord.replace("\'", "\\\'");
        myWord = myWord.replace("\"", "\\\"");
        myWord = myWord.replace("\t", "\\t");
        String program = "public class " + className + " {";
        program += "    public static void main(String[] args) {";
        program += "        System.out.println(\"" + myWord + "\");";
        program += "    }";
        program += "}";
        System.out.println(program);
        return program;
    }

}

为清楚起见,我没有使用org.apache.commons.lang.StringEscapeUtils。