0

I am currently beginning to learn Java code. One of the problems is to replace all tabs with * and all * with tabs. It was suggested that I first replace all tabs with the newline characters (\n). After that I could then replace * with tabs and tabs with *. I created a code I thought would work but after running it, I discovered it wasn't running properly. Can anyone help me fix the issue?

    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
        s.replaceAll("\t", "\n");
        s.replaceAll("\\*", "\t");
        s.replaceAll("\n", "\\*");
        System.out.println(s);

I have a feeling I am using the print statement incorrectly or maybe I am just setting this entire thing up wrong.

Example user input: **HelloThere* _ _ _ Bye*

Example output: _ _ HelloThere _ ***Bye _

The '_' are representing tabs.

Britni.M
  • 459
  • 1
  • 4
  • 6
  • Remember: *Strings are **immutable*** – Hovercraft Full Of Eels Oct 09 '16 at 22:23
  • 1
    So `s = replaceAll("\t", "\n");` and likewise for all the other `replaceAll` calls. – Hovercraft Full Of Eels Oct 09 '16 at 22:23
  • In the future, please avoid unclear statements in your question, such as `"... it wasn't running properly."` -- always tell us **how** it's not running properly. Here I *assume* that your code is not changing the String, but I hate making assumptions. – Hovercraft Full Of Eels Oct 09 '16 at 22:25
  • Thanks for the reply, and I am sorry for the vagueness. I am still getting the hang of everything. I will remember that for next time. Also, you were correct in that the string was not changing. As far as the code, are you saying I should change it from s.replaceAll to s = replaceAll? If so, an "undefined for the type replace" error occurs when doing so. – Britni.M Oct 09 '16 at 22:27
  • Sorry for the second reply. I actually just now replaced s=s.replace() with s=s.replace() and the code now works. Thank you for the help and again, I will remember to be more specific next time I ask a question. (: – Britni.M Oct 09 '16 at 22:33
  • You're welcome. Good luck. – Hovercraft Full Of Eels Oct 09 '16 at 22:34

0 Answers0