繁体   English   中英

从控制台Java读取带有换行符的字符串

[英]Reading a string with new lines from console java

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

one two three
four five six
seven eight nine

因此,我想每行读取一次并将每行放入数组中。 我该怎么读? 因为如果使用扫描仪,则只能读取一行或一个单词(下一行或下一行)。

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

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

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

回答第一个答案的评论中阐明的问题:

您必须为要阅读的每一行调用一次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即可。 我建议您在尝试使用ArrayList之前先阅读更多信息。

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

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

看下面的代码:

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();

 }

}

暂无
暂无

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

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