Home > Enterprise >  How to print the output one word at a time in JAVA?
How to print the output one word at a time in JAVA?

Time:10-25

I know how to print to console one line out of time. anyone that can help me learn how to print console word by word

private void intro() {
    try {
        List<String> allLines = Files.readAllLines(Paths.get("src/resources/GameStoryIntro.txt"));
        for (String line : allLines) {
            Thread.sleep(2000);
            System.out.println("\u001B[31m"   line   "\u001B[0m");
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    subMenu();
}

CodePudding user response:

you can use split method to split your line to words using separator you define and then print your words :

private void intro() {
    try {
        List<String> allLines = Files.readAllLines(Paths.get("src/resources/GameStoryIntro.txt"));
        for (String line : allLines) {
            Thread.sleep(2000);
            List<String> words = line.split(" "); // I used white space as separator
            for(String word : words) 
                System.out.println("\u001B[31m"   word   "\u001B[0m");
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    subMenu();
}

CodePudding user response:

using String split method to break the line to its words

for (String line : allLines) {   
    String[] lineWords = line.split(" ");   
    for (String word : lineWords ) {
      System.out.println(word);   
    }
}
  •  Tags:  
  • java
  • Related