使用来自控制台java的新行读取字符串

时间:2012-06-01 17:39:46

标签: java stringreader

我想读取此字符串(来自控制台而不是文件),例如:

one two three
four five six
seven eight nine

所以我想每行阅读它并将每一行放在一个数组中。 我怎么读呢?因为如果我使用扫描仪,我只能读一行或一个单词(下一行或下一行)。

我的意思是阅读例如:one two trhee \n four five six \n seven eight nine...

3 个答案:

答案 0 :(得分:8)

你应该自己做! 有一个similer的例子:

public class ReadString {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String userName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         userName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the name, " + userName);

   }

}  // end of ReadString class

答案 1 :(得分:2)

回答第一个答案评论中澄清的问题:

您必须为要读取的每一行调用Scanner的nextLine()方法一次。这可以通过循环完成。您将不可避免地遇到的问题是“我怎么知道我的结果数组应该大?”答案是你不知道你是否在输入中没有指定它。您可以修改程序输入规范以要求读取行数,如下所示:

3
One Two Three
Four Five
Six Seven Eight

然后你可以用这个读取输入:

Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
    result[i] = s.nextLine(); // each line of the input will be placed into the array.
}

或者,您可以使用名为ArrayList的更高级数据结构。创建时,ArrayList没有设置长度;您可以根据需要简单地添加信息,当您不知道要读取多少输入时,它非常适合读取输入。例如,如果我们使用您的原始示例输入:

one two trhee
four five six
seven eight nine

您可以使用以下代码阅读输入:

Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
    result.add(line);
}

因此,我们可以简单地将.add()的每一行简单地添加到ArrayList中,而不是创建一个固定长度的数组。我建议您在尝试使用ArrayLists之前阅读更多有关ArrayLists的信息。

tl; dr:您为要使用循环读取的每一行调用next()或nextLine()。

有关循环的更多信息:Java Loops

答案 2 :(得分:-1)

看看这段代码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class SearchInputText {

  public static void main(String[] args) {
    SearchInputText sit = new SearchInputText();
    try {
        System.out.println("test");
        sit.searchFromRecord("input.txt");
        System.out.println("test2");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void searchFromRecord(String recordName) throws IOException {
    File file = new File(recordName);
    Scanner scanner = new Scanner(file);
    StringBuilder textFromFile = new StringBuilder();
    while (scanner.hasNext()) {
        textFromFile.append(scanner.next());
    }
    scanner.close();

    // read input from console, compare the strings and print the result
    String word = "";
    Scanner scanner2 = new Scanner(System.in);
    while (((word = scanner2.nextLine()) != null)
            && !word.equalsIgnoreCase("quit")) {
        if (textFromFile.toString().contains(word)) {
            System.out.println("The word is on the text file");
        } else {
            System.out.println("The word " + word
                    + " is not on the text file");
        }
    }
    scanner2.close();

 }

}