Hi.
Why does the codegym says my program has infinite loop while it has not? Well it might have if someone inputs words eternally but if line is empty or null program does finish job and does meet requirements. I have tested it several times on IntelliJ IDEA and it works correctly. Any idea why it has infinite loop on codegym?
package com.codegym.task.task07.task0727;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Changing functionality
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<>();
while (true) {
try {
String s = reader.readLine();
if (s.isEmpty() || s.equals(null) || s == null || s.length() == 0) {
break;
} else {
list.add(s);
}
} catch (NullPointerException e) {
}
}
ArrayList<String> newList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).length() % 2 == 0) {
newList.add(list.get(i) + " " + list.get(i));
} else if (list.get(i).length() % 2 != 0) {
newList.add(list.get(i) + " " + list.get(i) + " " + list.get(i));
}
}
for (String s : newList) {
System.out.println(s);
}
}
}
/*Task: The program takes in strings until the user enters an empty string (by pressing Enter). Then it converts the strings to uppercase ("mother" becomes "MOTHER") and displays them.
New task: The program takes in strings until the user enters an empty string (by pressing Enter).
Then the program builds a new list. If a string has an even number of letters, then the string is duplicated. If the number of letters is odd, then the string is repeated three times.
The program displays the contents of the new list.
Example input:
Cat
Cats
I
Example output:
Cat Cat Cat
Cats Cats
I I I*/