2016-03-23 79 views
0

我想从文本处理器或其他输入复制的文本。 使用nextLine()只是介绍了第一行,它也不允许我使用StringBuffer。我还没有找到任何解决我的问题。如何使用命令控制台在java中输入文本?

这是我的代码:

public static void main (String args[]) { 
    Scanner keyboard= new Scanner(System.in); 
    StringBuffer lines= new StringBuffer(); 
    String line; 

    System.out.println("texto:"); 
    line= keyboard.nextLine(); 
    //lines= keyboard.nextLine(); //this doesn´t work 
    System.out.println(lines); 
} 

这里是我想要做什么的例子:

我从一个文本文件复制这样的文字:

ksjhbgkkg

sjdjjnsfj

sdfjfjjjk

然后,我把它粘贴在cmd上(我用Geany)。 我希望能够得到一个StringBuffer或类似的(东西我可以操纵)是这样的:

StringBuffer x = "ksjhbgkkgsjdjjnsfjsdfjfjjjk"

谢谢!

+0

如何将读取行添加到StringBuffer?如何阅读不只一行(因为你的例子中有三个)? – Tom

+0

为什么不使用java.util.Scanner? – Laurel

+0

@Laurel'扫描仪键盘=新扫描仪(System.in);'......对现有代码行有什么看法? – Tom

回答

0

尝试使用类似:

while(keyboard.hasNextLine()) { 
    line = keyboard.nextLine(); 
} 

然后,您可以保存这些行。 (例如数组/ ArrayList)。

0

可以追加keyboard.nextLine()到您的StringBuffer像这样:

lines.append(keyboard.nextLine()); 

的StringBuffer将接受一个String要追加所以这应该适合你的目的。

while (keyboard.hasNextLine()) { 
     lines.append(keyboard.nextLine()); 
} 
0

@Cache Staheli有正确的方法:

由@Cache表示这会看到这样的你可以用while循环使用。要详细说明如何将键盘输入放入您的StringBuffer,请考虑以下内容:

public static void main(String[] args) { 
    Scanner keyboard = new Scanner(System.in); 
    StringBuffer lines= new StringBuffer(); 
    String line; 

    System.out.println("texto:");  

    while(keyboard.hasNextLine()) { // while there are more lines to read 
     line = keyboard.nextLine(); // read the next line 
     if(line.equals("")) {  // if the user entered nothing (i.e. just pressed Enter) 
      break;     // break out of the input loop 
     } 

     lines.append(line);   // otherwise append the line to the StringBuffer 
    } 

    System.out.println(lines);  // print the lines that were entered 
    keyboard.close();    // and close the Scanner 
} 
+0

我试过你的代码,它让我引入新行,但我不能走出WHILE ......所以我从来没有达到System.out.println(行)。我试图添加一个条件,如:while(keyboard.hasNextLine()&& keyboard.nextLine!=“0”),但它没有工作...(我是一个begginer所以,也许不应该按Enter?)感谢您以前的回答! – Mercedes

+0

这是因为输入流'System.in'从来没有关闭,除非你自己关闭它(如果你保持Ctrl + D,你可以在Windows上执行此操作)。对于此程序的目的,您可能希望使用特定的条目来指示输入的结尾。例如,您可能希望这样做,以便如果用户按Enter键,则结束该程序。请参阅我的编辑答案的示例,并注意Scanner.nextLine()方法将消耗输入中的新行,因此我们要检测空字符串“”而不是新行字符“\ n”。 – Matt

相关问题