fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List<String> list = Arrays.asList();
  13. Scanner scanner = new Scanner(System.in);
  14. String in;
  15. System.out.println("Type a string and hit enter to enter it into the list. Type 'exit' when you are done.");
  16. while (scanner.hasNextLine() && !(in = scanner.nextLine()).equalsIgnoreCase("exit")) {
  17. list.add(in);
  18. }
  19. System.out.println("Compiling now...");
  20. System.out.println(toString(list, ", ", ". The end."));
  21. scanner.close();
  22. }
  23.  
  24. public static String toString(List<String> list) {
  25. return toString(list, ", ", null);
  26. }
  27.  
  28. public static String toString(List<String> list, String separator, String ending) {
  29. if (list == null || list.isEmpty() || list.get(0) == null)
  30. return "";
  31. if (list.size() == 1)
  32. return list.get(0);
  33. if (list.size() == 2)
  34. return list.get(0) + " and " + list.get(1);
  35. StringBuilder str = new StringBuilder(list.get(0));
  36. for (int i = 1; i < list.size() - 1; i++)
  37. str.append(separator).append(list.get(i));
  38. str.append(separator).append("and ").append(list.get(list.size() - 1)).append((ending != null ? ending : ""));
  39. return str.toString();
  40. }
  41.  
  42. }
Runtime error #stdin #stdout #stderr 0.07s 2184192KB
stdin
aw
This
is
a
string
This
is
a
string
exit
stdout
Type a string and hit enter to enter it into the list. Type 'exit' when you are done.
stderr
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at Ideone.main(Main.java:17)