0

I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:

import java.io.*;

public class Instruction {
   public String[] instructionList;

   public String[] readFile() throws IOException {
      FileInputStream in = new FileInputStream("directions.txt");
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      int n = 5;
      instructionList = new String[n];

      for (int j = 0; j < instructionList.length; j++) {
          instructionList[j] = br.readLine();
      }
      in.close();   
      return instructionList;
  }

}

The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.

import java.util.Arrays;
public class RoverCommand {

  public static void main(String[] args) throws Exception {
      Instruction directions = new Instruction();
      directions.readFile();

      String[] directionsArray;
      directionsArray = directions.returnsInstructionList();

      System.out.println(Arrays.toString(directionsArray));
  }

}

What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?

15
  • Your question is not clear to me. What are you trying to achieve ?
    – Dici
    Sep 28, 2014 at 22:00
  • I want to read a text file, store the contents of that file in an array, and have that array accessible to other objects. I am attempting to do that Mars Rover coding challenge. I also have no experience in Java.
    – yesyouken
    Sep 28, 2014 at 22:11
  • Does your code work? This seems like a fine way to do it. Alternatively, you can return the array directly from readFile(), but this is a design decision that depends on other constraints. Sep 28, 2014 at 22:13
  • yes it does, I have no changed it so that readFile() returns the array directly.
    – yesyouken
    Sep 28, 2014 at 22:16
  • What is the best way to make that array accessible to other objects within main?
    – yesyouken
    Sep 28, 2014 at 22:17

3 Answers 3

1

You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.

// Client.java
import java.io.IOException;

public class Client {
    public static void main(String args[]) {
        try {
            InstructionList il = new InstructionList();
            il.readFile("C:\\testing\\ints.txt", 5);

            int[] integers = il.getInstructionsAsIntegers();

            if (integers != null) {
                for (int i : integers) {
                    System.out.println(i);
                }
            }
        } catch (IOException e) {
            // handle
        }
    }
}


// InstructionList.java
import java.io.*;

public class InstructionList {
    private String[] instructions;

    public void readFile(String path, int lineLimit) throws IOException {
        FileInputStream in = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        instructions = new String[lineLimit];

        for (int i = 0; i < lineLimit; i++) {
            instructions[i] = br.readLine();
        }

        in.close();
    }

    public String[] getInstructionsAsStrings() {
        return instructions; // will return null if uninitialized
    }

    public int[] getInstructionsAsIntegers() {
        if (this.instructions == null) {
            return null;
        }

        int[] instructions = new int[this.instructions.length];

        try {
            for (int i = 0; i < instructions.length; i++) {
                instructions[i] = new Integer(this.instructions[i]);
            }
        } catch (NumberFormatException e) {
            return null; // data integrity fail, return null
        }

        return instructions;
    }
}
8
  • While the OP's code can be improved with some basic exception handling (especially to avoid resource leaks), this doesn't address the original question regarding design issues. Sep 28, 2014 at 22:42
  • @Code-Apprentice I'm not really sure what he's having trouble with. If he needs one object to access the first and second elements, he can just use the index operator[] to get those. Like getInstructionsAsIntegers()[1]. What is your solution to his problem? Sep 28, 2014 at 23:08
  • I probably would save the return value in a variable and then index it, rather than indexing the method call directly. Sep 28, 2014 at 23:39
  • It seems that the OP's problems are centered around understanding how to use objects and methods (and designing the classes in the first place). Sep 28, 2014 at 23:39
  • Not a bad idea, except for when you need to index the integers. You would need a collection for both strings and integers. But it's great for removing the overhead of future calls to getInstructionsAsDataType(). He did say he was new to Java, but I don't know if he is new to object-oriented programming in general. I think he's just asking the Java community here if there is a better alternative to what he is doing. What's the best way to do that? But I could be wrong. Sep 28, 2014 at 23:45
0

check instructionList is null or not. if it is null, call readFile method.

public String[] returnsInstructionList() {
      if (instructionList== null){
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}

because of readFile can throw exception, it would be good to use one extra variable. like:

private boolean fileReaded = false;
public String[] returnsInstructionList() {
      if (!fileReaded){
          fileReaded = true;
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}

and if readFile can be run concurrently, easiest way to make function synchronized, like

private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
    .
    .
    .        
}
public synchronized String[] returnsInstructionList() {
      if (!fileReaded){
          fileReaded = true;
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}
0

There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.

I would :

public String[] getContentsFromFile(String fileName) throws IOException {
  FileInputStream in = new FileInputStream(fileName);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  int n = 5;
  instructionList = new String[n];

  for (int j = 0; j < instructionList.length; j++) {
      instructionList[j] = br.readLine();
  }
  in.close();       
  return instructionList;
}

Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.

Eg

public class Foo {
   public ReturnForFoo returnAStringOrIntger(boolean val) {
      if(val){
         return new ReturnForFoo("String", ValueType.STRING) ;
      }
      return new ReturnForFoo(10, ValueType.INTEGER); //int
   } 
}

 public class ReturnForFoo {
     Object value;
     ValueType type;

     public ReturnForFoo(Object value, ValueType type) {
         this.value=value;
         this.type=type
     }
     // Asume you have getters for both value and value type
     public static ENUM ValueType {
          STRING,
          INTEGER,
          UNKNOWN
     }
 }

This code is in your main.

 Foo foo = new Foo();
 String value;
 int val;
 ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
 // NOTE you can use switch instead of if's and else if's. It will be better
 if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
    val = (int) returnForFoo.getValue();
 } else if(returnForFoo.getValueType().equals(ValueType.STRING)){
    value = (String) returnForFoo.getValue(); 
 } else {
    // UNKOWN Case
 }
8
  • The first sentence is wrong and the last part is a nasty solution.
    – Dici
    Sep 28, 2014 at 22:07
  • @Dici can you help us improve the answer as to how we can use generics. Sep 28, 2014 at 22:11
  • Well, I read the description of the problem and it seems to be a bad idea to store all the lines in a single array. It would be more logical to parse the file with a Scanner and store the values in some variables of the expected type, since you know precisely how the input looks like.
    – Dici
    Sep 28, 2014 at 22:18
  • Im taking about a function returning generics and not file addling and how to store the file. is there a better way to do this Another approach i know is that we can wrap the return into a new class which has an enum of type. I want to know a better way of doing generics. Sep 28, 2014 at 22:21
  • 1
    An array of Object is not generic, genericity is about writing some code depending on an unknown type taken as parameter. In my opinion you should not try to store Integers and Strings in the same data structure in the first place, so I won't propose any solution to do it.
    – Dici
    Sep 28, 2014 at 22:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.