0

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

Bart
  • 18,467
  • 7
  • 66
  • 73
user1253201
  • 91
  • 2
  • 4
  • 8

3 Answers3

8

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
Victor
  • 7,620
  • 14
  • 74
  • 121
  • that can only read one line what i mean if to read : one two three \n four five six \n seven eight nine – user1253201 Jun 01 '12 at 17:53
  • I'm honestly having trouble understanding what you want. Am I correct in assuming that you want to read "one", "two", "three" into an array but each word is on the same line line, then the next line contains "four", "five", "six" and you want each of those values to be in the array as well? – Alex Lynch Jun 01 '12 at 18:26
  • yes split the text every new line so one two three will array[0] four five six array[1], etc... but I cant even read the text cause using nextLine() only reads the first line which is one two three, then how can I read the others other lines? – user1253201 Jun 01 '12 at 18:30
  • Try putting the readLine() in a while until this returns null. It's your homework, so you need learn! ;) – Victor Jun 01 '12 at 19:43
3

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

Alex Lynch
  • 931
  • 5
  • 11
-1

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

 }

}