简体   繁体   中英

Read text file with scanner and insert line break every 10 characters

Having trouble with a java exercise, I need to take input from a text file and print the contents out but insert a new line break every 10 characters, for example it should read in: I like to eat ice cream

as

I like to eat ice cr eam

heres my current solution so far

public class practice {

public static void main(String[] args) {
Scanner input = new Scanner (practice.class.getResourceAsStream("hello.txt"));
String currentLine = "";
String lineTen = "\n";
int charCount = 0;

while (input.hasNext()) {
    currentLine =  input.nextLine();
    System.out.println(currentLine);
    //charCount++;
    for (int i = 0; i < currentLine.length(); i++) {
        if (currentLine.charAt(i) !=  ' ' && currentLine.charAt(i) != '\n') 
        {
            charCount++;
        }
        if (charCount > 20) {
        currentLine = ("\n");
        }
        }
    }
    System.out.println(currentLine);
    System.out.println(charCount);
}
}

Any suggestions would be appreciated.

Why are you excluding spaces if you are counting them in the example? you should remove that in the code, you can building a string then print it when its complete as the following:

try (Scanner input = new Scanner(new File("test.txt"))) {
        String currentLine = "";
        String result = "";
        int charCount = 0;
        while (input.hasNext())
            currentLine += input.nextLine() + " ";
            //charCount++;
        for (int i = 0; i < currentLine.length(); i++) {
            if (currentLine.charAt(i) != '\n') { 
                if (charCount >= 20) {
                    result+= "\n" + currentLine.charAt(i);
                    charCount = 1;
                }
                else {
                    result += currentLine.charAt(i);
                    charCount++;
                }
            }
            else
                charCount++;
        }
        System.out.println(result);
    }

also use try-with-resources as shown in the code above.

input:

I like to eat ice cream

output:

I like to eat ice cre
am 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM