Java:.charAt无法识别空格字符

时间:2018-04-21 00:23:47

标签: java string charat

我讨厌在这里打扰,但是我的个人项目一直在回归一个顽固的错误。因为我是一名计算机科学专业的学生,​​所以我和一些同学一起看过这本书,但也没有用。

问题是我正在尝试编写一个带有String的程序,并且每40个字符将该段存储到数组中的一个点,这样最终的print语句只需要打印出数组中的每个元素在新行上,整个文本长度将保持在40个字符以内。

一旦我修改了所述程序,就会出现错误,所以如果字符串中的第40个字符是一个字母,那么程序就会知道它正在切断一个单词。因此,为了违背这一点,我从那个位置向后搜索到最后一个空间的索引,并在那里切割线。然后将剩余的单词添加到新行,程序继续。

但事实并非如此。无论出于何种原因,在搜索字符串时都找不到空格字符,尽管很多都存在。

以下是问题产生的特定部分:

//the following while loop searches for the last index in the string that
// was a space, therefore finding the beginning of the cut word. 
//Also account for the chance the index reaches the start of the string
                while(cutChar != ' ' && temp > 0){
                    temp--;
                    cutChar = sentence.charAt(temp);

                    //minuses the line of the char to be added to the next line
                    newLine = newLine.substring(0, newLine.length() - 1);
                }

以下是这个程序的完整性,对高天的评论编码:

import java.util.*;
public class errorCheck{
    public static void main (String [] args) {

    //original sentence
    String sentence = "This test sentence should cut off properly at every 40th character and add any cut words to the next line.";

    //array to store each line
    ArrayList <String> words = new ArrayList<String>();

    //current line being filled
    String newLine = "";

    //individual character being read from the sentance string
    char character = ' ';

    //string to preserve any word severed when a new line is created
    String cutWord = "";

    //int to keep track of how many indexes to move over
    int cutAdd = 0;

    //char to keep track of the chars in the word being cut off at the end of the line
    char cutChar = ' ';

    //int to keep track of temporary place when searching for the beginning of the cut word
    int temp = 0;

    for (int i = 0; i < sentence.length(); i++){
        //examines the chars one by one in the sentance
        character = sentence.charAt(i);

        //makes sure each line is max 40 chars long
        if(i%40 == 0 && i > 1){
            //if the char at the 40 mark is a space or coma, add it to the line and start a new line
            if (character == ' ' || character == ','){
                newLine += character;
                words.add(newLine);
                newLine = "";
            }
            //else (aka the line stops in the middle of a word)
            else{
                //sets temporary character and index to current one
                cutChar = character;
                temp = i;

                //the following while loop searches for the last index in the string that was a space, therefore finding the beginning of the cut word. Also account for chance the index reaches the start of the string
                while(cutChar != ' ' && temp > 0){
                    temp--;
                    cutChar = sentence.charAt(temp);

                    //minuses the line of the char to be added to the next line
                    newLine = newLine.substring(0, newLine.length() - 1);
                }

                //once a space was found and the while loop broken, add a index to begin reading the severed word completely
                temp++;
                cutWord = "";
                //this while loop makes sure to read until it comes across another space or reaches the end of the string (in the even that this cut word happens to be the final word)
                while(cutChar != ' ' && sentence.length() >= temp){
                    //examines the chars in the sentance, adds it to the cut word, and increases the index
                    cutChar = sentence.charAt(i);
                    cutWord += cutChar;
                    temp++;
                    if (temp >= 40){
                        //counts the additional indexes to be added to the normal index when resumed
                        cutAdd++;
                    }
                }

                //after exiting the loop, the string "cutWord" should be the full word cut between the two lines

                //adds the new line (minus the chars taken for the cut word) 
                words.add(newLine);
                //starts a new line with cutWord being the start
                newLine += cutWord;
                //increases index by amount of new characters
                i += cutAdd;

                //resets the cut variables
                cutWord = "";
                cutAdd = 0;
            } 
        }

        //This loop makes sure that the final char is always added
        else if (i == (sentence.length() - 1)){
            newLine += character;
            words.add(newLine);
        }

        //if no other condition is met, the current character is simplily added to newLine
        else{
            newLine += character;
        }
    }

    //after all that, there should be an arraylist with a line for each element
    String[] wordsArray = new String[words.size()];
    //turn that arraylist to a regular one (because ideally in the end it's going to be sent over somewhere else)
    wordsArray = words.toArray(wordsArray);

    //should print out the sentance in lines that are 40 chars or less
    for (int i = 0; i < wordsArray.length; i++){
        System.out.println(wordsArray[i]);
    }

}
}

目前,while循环无法停止在String中的空格字符处,输出如下所示:

ERROR

有人知道解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

我认为检查char是空格还是逗号的if语句实际上应该是while循环。并且继续减少我,而char再次是空间。

   if (character != ' ' && character != ','){
            i--;
            character = sequence.charAt(i);
            while(character != ' ' && character != ','){
                i--;
                character = sequence.charAt(i);
            }
        }
    newLine += character;
    words.add(newLine);
    newLine = "";

你摆脱了else条款。现在无法测试它,所以告诉我它的工作原理。

答案 1 :(得分:0)

首先,你需要很多代码。我完全删除了以下部分。我也删除了临时变量。

            //once a space was found and the while loop broken, add a index to begin reading the severed word completely
            temp++;
            cutWord = "";
            //this while loop makes sure to read until it comes across another space or reaches the end of the string (in the even that this cut word happens to be the final word)
            while(cutChar != ' ' && sentence.length() >= temp){
                //examines the chars in the sentance, adds it to the cut word, and increases the index
                cutChar = sentence.charAt(i);
                cutWord += cutChar;
                temp++;
                if (temp >= 40){
                    //counts the additional indexes to be added to the normal index when resumed
                    cutAdd++;
                }
            }

            //after exiting the loop, the string "cutWord" should be the full word cut between the two lines

            //adds the new line (minus the chars taken for the cut word) 
            words.add(newLine);
            //starts a new line with cutWord being the start
            newLine += cutWord;
            //increases index by amount of new characters
            i += cutAdd;

            //resets the cut variables
            cutWord = "";
            cutAdd = 0;

此外,您的问题在于如何跟踪您阅读句子的位置。如果你向后移动几个空格,那么它现在<40,因此将在下一行上过早地重新触发,这将导致奇怪的行为。所以我添加了一个名为readChars的独立变量。问题解决了以下代码现在有效。

import java.util.*;
public class errorCheck{
    public static void main (String [] args) {

    //original sentence
    String sentence = "This test sentence should cut off properly at every 40th character and add any cut words to the next line.";

    //array to store each line
    ArrayList <String> words = new ArrayList<String>();

    //current line being filled
    String newLine = "";

    //individual character being read from the sentance string
    char character = ' ';

    //string to preserve any word severed when a new line is created
    String cutWord = "";

    //int to keep track of how many indexes to move over
    int cutAdd = 0;

    //char to keep track of the chars in the word being cut off at the end of the line
    char cutChar = ' ';

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

        //examines the chars one by one in the sentance
        character = sentence.charAt(i);

        //makes sure each line is max 40 chars long
        if(charsRead >= 40 && i > 1){
            //if the char at the 40 mark is a space or coma, add it to the line and start a new line
            if (character == ' ' || character == ','){
                newLine += character;
                words.add(newLine);
                newLine = "";
            }
            //else (aka the line stops in the middle of a word)
            else{
                //sets temporary character and index to current one
                cutChar = character;

                //the following while loop searches for the last index in the string that was a space, therefore finding the beginning of the cut word. Also account for chance the index reaches the start of the string
                while(cutChar != ' ' && i > 0){
                    i--;
                    cutChar = sentence.charAt(i);

                    //minuses the line of the char to be added to the next line
                    newLine = newLine.substring(0, newLine.length() - 1);
                }

                //after exiting the loop, the string "cutWord" should be the full word cut between the two lines

                //adds the new line (minus the chars taken for the cut word) 
                words.add(newLine);
                newLine = "";
            } 

            charsRead = 0;
        }

        //This loop makes sure that the final char is always added
        else if (i == (sentence.length() - 1)){
            newLine += character;
            words.add(newLine);
        }

        //if no other condition is met, the current character is simplily added to newLine
        else{
            newLine += character;
        }
    }

    //after all that, there should be an arraylist with a line for each element
    String[] wordsArray = new String[words.size()];
    //turn that arraylist to a regular one (because ideally in the end it's going to be sent over somewhere else)
    wordsArray = words.toArray(wordsArray);

    //should print out the sentance in lines that are 40 chars or less
    for (int i = 0; i < wordsArray.length; i++){
        System.out.println(wordsArray[i]);
    }

}
}

上面的代码产生以下输出。

This test sentence should cut off
properly at every 40th character and
add any cut words to the next line.

答案 2 :(得分:0)

这是为这项任务重新发明的疯狂代码。为什么不使用这样的东西(WordUtils来自Apache Commons Text):

String wrapped = WordUtils.wrap(theText, 40, “~~~”, true); 
String[] split = wrapped.split(“~~~”);