0

I have written a code which transforms all the new line characters to comma. If a character is '\n' it will change it to ','. But I am having problems entering my sample data. I think Netbeans takes spaces as new line characters. Pressing enter at the run section inputs the data I have written instead of creating a new line. What should I do ?

I am also open to suggestions about my code.

This is the code:

package newlinetocomma;

import java.util.Scanner;

/**
*
* @author sametsahin
*/
public class NewLineToComma {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter a text: ");
    String textWithNewLines = scanner.next();

    char[] textWithNewLinesAsArray = textWithNewLines.toCharArray();

    for (int i = 0; i < textWithNewLinesAsArray.length; i++) {

        if (textWithNewLinesAsArray[i] == '\n') {

            textWithNewLinesAsArray[i] = ',';

        }

    }

    for (int i = 0; i < textWithNewLinesAsArray.length; i++) {

        System.out.print(textWithNewLinesAsArray[i]);

    }

  }

}
SametSahin
  • 571
  • 3
  • 7
  • 24
  • Not sure but I don't think you can enter a paragraph with new lines via Scanner, you will need to read it from text document I believe. – Eray Balkanli Apr 04 '18 at 21:00
  • Possible duplicate of [Scanner doesn't see after space](https://stackoverflow.com/questions/19509647/scanner-doesnt-see-after-space) – Joe C Apr 04 '18 at 21:01

1 Answers1

0

If you want to input a multiline text you can make use of the useDelimiter(String pattern) function. You could split on a specific char sequence you will (most likely) never enter like Ctrl+D (Unix) Ctrl+Z (Windows). As the delimiter you can than match to end of file.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in).useDelimiter("\\Z");
    String text = scanner.next().trim().replaceAll("\n",",").replaceAll("\r","");
    System.out.println(text);
}

Keep in mind that you have to submit each line (press enter) before it will be recognized by the scanner. The line you press the exit shortcut will not be added to the result of next().

Notice: On windows you also have to submit the Ctrl+Z signal manually.

pixix4
  • 1,271
  • 1
  • 13
  • 13
  • I have tride using `useDelimiter("\\^D")` but it still takes input what I have written when I press enter. I want to be able to enter a new line in the run section. – SametSahin Apr 05 '18 at 08:49
  • If you want to interprete each line after you pressed enter you could use a `while` loop around [`scanner.nextLine()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--). – pixix4 Apr 05 '18 at 09:33