0

I am getting output from my java program in below format.

[race, care, acre][act, cat]

Expected: Each array elements in different line.

race care acre
act cat

I already tried to print but getting.

race care acre act cat

Is there any way around so i can get expected results. Below is the gist of my code. Thanks

    public static void main(String args[]) {

        try {
            Scanner sc = readWords();
            Map<String, List<String>> wordAnagramPairs = new HashMap<>();
            wordAnagramPairs = mapAnagrams(sc);
            for (String anagram : wordAnagramPairs.keySet()) {
                if (wordAnagramPairs.get(anagram).size() > 1) {
                    System.out.print(wordAnagramPairs.get(anagram));
//                    for(String anagrams : wordAnagramPairs.get(anagram)){
//                        System.out.print(anagrams + " ");
//                    }
                }
            }



        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
        }
    }

3 Answers 3

1

use print with \n new line

for (String anagram : wordAnagramPairs.keySet()) {
    if (!wordAnagramPairs.get(anagram).isEmpty()) {
        for (String word : wordAnagramPairs.get(anagram)) {
         System.out.print(word+" ");
        }
    }
    System.out.print("\n");
 }
Sign up to request clarification or add additional context in comments.

Comments

1

You need to make you for statement use println if you want to print each element on a new line:

for(String anagrams : wordAnagramPairs.get(anagram)){
                        System.out.println(anagrams + " ");
                   }

If you want to print out each array element on a single line, but have each array on a separate line, you would do something like this:

for (String anagram : wordAnagramPairs.keySet()) { 
                //You need to make this 0 rather than 1 if you want to print 
                //out an array with one element
                if (wordAnagramPairs.get(anagram).size() > 0) {
                    for(String anagrams : wordAnagramPairs.get(anagram)){
                        System.out.print(anagrams + " ");
                    }

                }
            //you need to put a print statement outside the second for loop
            System.out.println("");
            }

Comments

0

"\n" is a sign of a newline. Is that what you are looking for? or use println instead of print

Take a look here (escape characters sub-topic) if you need an explaination https://docs.oracle.com/javase/tutorial/java/data/characters.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.