简体   繁体   English

如何在Netbeans的运行部分输入新行?

[英]How can I enter a new line at Netbeans' run section?

I have written a code which transforms all the new line characters to comma. 我已经编写了将所有新行字符转换为逗号的代码。 If a character is '\\n' it will change it to ',' . 如果字符是'\\n' ,它将更改为',' But I am having problems entering my sample data. 但是我在输入样本数据时遇到问题。 I think Netbeans takes spaces as new line characters. 我认为Netbeans将空格作为换行符。 Pressing enter at the run section inputs the data I have written instead of creating a new line. 在运行部分按Enter输入我编写的数据,而不是创建新行。 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]);

    }

  }

}

If you want to input a multiline text you can make use of the useDelimiter(String pattern) function. 如果要输入多行文本,可以使用useDelimiter(String pattern)函数。 You could split on a specific char sequence you will (most likely) never enter like Ctrl+D (Unix) Ctrl+Z (Windows). 您可以分割一个特定的字符序列,您将(很可能)永远不会像Ctrl + D(Unix)Ctrl + Z(Windows)那样输入。 As the delimiter you can than match to end of file . 作为分隔符,您可以匹配到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. 请记住,必须先提交每行(按Enter键),扫描仪才能识别它。 The line you press the exit shortcut will not be added to the result of next() . 您按下退出快捷方式的行不会添加到next()的结果中。

Notice: On windows you also have to submit the Ctrl+Z signal manually. 注意:在Windows上,您还必须手动提交Ctrl + Z信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM