Reading a string with new lines from console java

2019-09-01 04:13发布

I want to read this string (from console not file) for example:

one two three
four five six
seven eight nine

So I want to read it per line and put every line in an array. How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).

what I mean is to read for example : one two trhee \n four five six \n seven eight nine...

3条回答
\"骚年 ilove
2楼-- · 2019-09-01 05:05

You should do by yourself! There is a similer example:

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
查看更多
虎瘦雄心在
3楼-- · 2019-09-01 05:08

To answer the question as clarified in the comment on the first answer:

You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:

3
One Two Three
Four Five
Six Seven Eight

And then you can read the input with this:

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.
}

Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:

one two trhee
four five six
seven eight nine

You can read the input with the following code:

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

So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.

tl;dr: You call next() or nextLine() for each line you want to read using a loop.

More information on loops: Java Loops

查看更多
霸刀☆藐视天下
4楼-- · 2019-09-01 05:17

Look at this code:

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

 }

}
查看更多
登录 后发表回答