1

Hello basically my aim is to read a txt file store it within an array and print the array element after the method argument. the text file is formated as shown (a space between each string on a line)

alan 1000

lee 20

rodney 28

e.g. if my argument was lee, the method should print out 20. If rodney then 28

public class practice
{
public void dataReader(String fName, String pname)
{
    try
    {
      FileReader fr=new FileReader(fName);
      BufferedReader br=new BufferedReader(fr);

      String[] a={};
      String line= br.readLine();


      while(line !=null)
      {
           a= line.split(" "); // deliminator white space
      }

      for(int i=0; i <a.length; i++)
      {
          if(a[i].equals(pname))
          {
              System.out.println(a[i]+1);
          }
      }
    }

    catch(IOException e)
    {
    }
}
2
  • 2
    Use formatting, Java classes start with upper-case letter (convention) Commented Aug 13, 2012 at 18:19
  • If this is homework it should be tagged as such. Commented Aug 13, 2012 at 18:29

2 Answers 2

5

The code you posted is not working because you only ever read the first line, then loop over that line forever.

Your code, trimmed and annotated:

String line= br.readLine(); // returns the first line of the file

while(line !=null) { // checks if the line is null - it's not at the first line
    a= line.split(" "); // deliminator white space
}
// we never get here, because nowhere in the loop do we set line to null

You need to call br.readLine() in a loop until it returns null, something like this:

BufferedReader br=new BufferedReader(new FileReader(fName));

String line= br.readLine(); // reads the first line, or nothing

while(line != null) {
    a= line.split(" "); // deliminator white space
    String[] arr = line.split("\\s+"); // splits a string by any amount of whitespace
    if(arr.length >= 2 && arr[0].equals(lookup)) {
        System.out.println(arr[1]);
    }

    line = br.readLine(); // this will eventually set line to null, terminating the loop
}

The for loop in your original code will not work, if you ever hit it your output would be lee1 or rodney1 respectively. If you changed it to arr[i+1] instead, which I assume you were trying to do, it would crash with an IndexOutOfBoundsException if ever the last item in the array matched pname.


Orginal Answer

This is an ideal use case for a Scanner. It "scans" a string or file for the contents you're looking for, dramatically simplifying file parsing for many use cases, in particular whitespace-delimited files.

public void searchFile(String fName, String lookup){
  Scanner in = new Scanner(new File(fName));
  // Assumes the file has two "words" per line
  while(in.hasNext()){
    String name = in.next();
    String number = in.next():
    if(name.equals(lookup){
      System.out.println(number);
    }
  }
}

If you cannot use scanner to parse each line, you can still use it to simplify reading each line, and then do whatever more complex parsing of the line needs to be done, like so:

public void searchFile2(String fName, String lookup){
  Scanner in = new Scanner(new File(fName));
  while(in.hasNextLine()){
    String line = in.nextLine();
    String[] arr = line.split("\\s+"); // splits a string by any amount of whitespace
    if(arr[0].equals(lookup)){
      System.out.println(arr[1]);
    }
  }
}

As an aside, if you know the names will be unique, you can use a Map (specifically, a HashMap) to store and lookup mappings like names to numbers efficiently. So instead of having a method which takes a filename and a name to lookup, you have a method which parses the file and returns a mapping of all names to numbers, then you can simply call map.get("name") on the returned map to get a given person's number efficiently, without having to re-read the file every time.

Sign up to request clarification or add additional context in comments.

Comments

2

You should use a Dictionary object

Dictionary<String, Integer> wordPairs = new Dictionary<String, Integer>();
while(br.ReadLine())
{
    wordPairs.put(a[0], Integer.parseInt(a[1]));
}

To get the number, you simply lookup in the dictionary by the key name.

public int getNumber(string name)
{
    return wordPairs.get(name);
}

7 Comments

Any one of the Map-type collections would work fine for this.
Note that Dictionary is obsolete, and should not be used. Objects implementing java.util.Map should be used instead. Additionally, you should avoid starting method and variable names with upper case letters, as they can be easily confused with class names. Finally, you cannot use int in a generic, you must use the wrapper class Integer.
thanks for the help guys but the task requires use of line.split. i agree scanner would be the best option however in this case i cannot use it
@mathew it would be helpful if you clarified exactly what issue you are struggling with. I have posted an alternative that uses String.split() in my answer.
thanks again although the use of scanner is completly not allowed as the task specifies. Im just wondering why the code i had written does not work, by my understanding it reads each line and splits each string in the array, and attempts to search through the array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.