(main method calling classes)
import java.io.*; public class bob { public static void main(String[] args){ new bert(); new larry();
(creates a file and copys string to it)
public class larry{ bert bertObj = new bert(); public larry(){ try{ File file = new File("text.txt"); if(!file.exists()) file.createNewFile(); PrintWriter pw = new PrintWriter(file); for(String x: bertObj.string){ pw.println(x); } pw.close(); }catch(IOException e){ e.printStackTrace(); } } }
(reads a file and copies it into a string array) (i havent initialised the string, i think that maybe the error, though i dont know how many values i will be storing inside it so i do not wish to do String string[] = new String[100] for example.... what else can i do?)
public class bert { String string[]; public bert(){ BufferedReader br = null; try{ br = new BufferedReader(new FileReader("C:\\Program Files\\Java\\jdk1.8.0_101\\THIRDPARTYLICENSEREADME.txt")); int counter = 0; while((string[counter] = br.readLine()) != null) { counter++; } for(int x = counter; x < 4000; x++) string[x] = ""; }catch(IOException e){ e.printStackTrace(); }finally{ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Asked
Active
Viewed 94 times
-1
-
1The simplest solution to this is to get rid of arrays and use an ArrayList or Strings. I do not know what you think `for(int x = counter; x < 4000; x++) string[x] = "";` will do – Scary Wombat Aug 26 '16 at 00:15
1 Answers
-1
In class bert, your String[] is never initialized before you try to access it in this line:
while((string[counter] = br.readLine()) != null)
Just like you initialized bert in the larry class, you need to initialize the String[] in the bert class.
Turn this line:
String [] string;
Into:
String[] string = new String[5]; // 5 is an arbitrary number I chose, you need to choose how many strings you will be holding in that array
Sorry, did not fully read your comments. Instead of a static array, try using an arraylist. This does not work the same as an array.
To give you a short example:
ArrayList<String> string = new ArrayList();
string.add("hello"); // string now has a string "hello"
string.add("world"); // string now has a string "hello" followed by a string "world"
for(int i = 0; i < string.size(); i++) {
System.out.println(string.get(i)); // gets position i from the array and prints it. Will print hello then a new line then world.
}
More on the arraylist here:

Cmoraski
- 78
- 4
-
-
No problem, I hate when people mark as duplicate, just answer the question, these are sometimes very specific! – Cmoraski Aug 26 '16 at 01:02