• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about this array class

 
Tom Chot
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
i know that i am not supposed to ask this kind of question
but i don't really know how to fix the error in this below code.
--------------------------------------------------------------------
import java.io.*;
class testArray
{
boolean check = true;
String[] c;
String[] read;
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int i = 0;

public static void main(String [] args)
{
int[] dog;

while(check == true)
{

System.out.println("Type anything : ");
read[i] = b.readLine();
System.out.println("more? :");
c[i] = b.readLine();

if((c.charAt(0) == 'n') || (c.charAt(0) == 'N'))
{
check = false;
}
else
{
check = true;
}


}

for(int j = 0; j < read.length() ; j++)
{
System.out.println("name: " + read[j]);
}
}
}
----------------------
Very Very thx and really appreciate..
Regards,
TOm
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,
Welcome to JavaRanch!
The most obvious problem with this program is that "read" is a null reference; you haven't allocated an array for it to point to, so when you try to use it, you get a NullPointerException. So you need to allocate some space, like

As soon as you do allocate a fixed-sized array, you'll have the problem that the user may type in more lines of text than there are array elements, and the you'll get ArrayIndexOutOfBoundsException; for this reason, you should consider changing this program to use a java.util.ArrayList instead of a raw array.
 
Tom Chot
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in this code..
i wanna use the dynamic array so that i don't need to worry about the size of the array?
Regards,
Tom
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tom Chot:

String[] c;
String[] read;
c[i] = b.readLine();

if((c.charAt(0) == 'n') || (c.charAt(0) == 'N'))

instead of

try
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic