Array *not throwing out of bounds exception - java

I'm trying to learn about exception handling. I can't seem to get
String[] a = names(scnr); To throw an out of bounds exception when it goes beyond 3 elements. I know, most people hate the out of bounds error and I'm trying to make it happen and for the life of me I cannot figure out what I'm doing wrong. Been at it all day and googled all kinds of stuff. But I cannot seem to find exactly what I'm looking for. So I could use some help and perspective.
So I'm inputting a full string that I'm delimiting (trim and splitting) based on commas and spaces and then the pieces are being stored into an array (String []name), then passed to main to be output with String[] a. So it's not erroring when I go beyond 3 elements no matter how I do it. I can just not display anything beyond a[4]. But that's not really what I'm trying to do. Its my first java class so be gentle haha.
Any suggestions?
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}

If I understand you correctly, you want to throw an ArrayOutOfBoundsException if the names array does not contain exactly 3 elements. The following code is the same as the one you wrote with an if-statement to do just that.
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
if (name.length != 3) {
throw new ArrayIndexOutOfBoundsException();
}
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}

If you want java to throw an ArrayIndexOutOfBoundException you have to preserve the created names instance and let java copy the array into your names array:
String[] names=new String[3];
String[] rawElements=rawData.trim().split("[\\s,]+");
System.arraycopy(rawElements, 0, names, 0, rawElements.length);
output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at stackoverflow.OutOfBound.main(OutOfBound.java:8)

As far as I understand, you are expecting an exception (ArrayIndexOutOfBoundsException) to the thrown at line
name = rawData.trim().split("[\\s,]+");
with an argument that the size of array (name) is fixed to 3, and when if the input is beyond 3 then the exception must be thrown; which is not the case.
The reason is in the way assignment happens in java. When you declare String[] name = new String[3];, then an object is created in java heap and its reference is assigned to variable name which is in stack memory.
And when this line name = rawData.trim().split("[\\s,]+"); gets executed then a new array object is created in heap and the variable name starts pointing to the newly created array object on heap. Note: the old object will get available for garbage collection after some time.
This eventually changes the length of the array variable (name) and you do not get any ArrayIndexOutOfBoundsException.
You can understand this more clearly by printing the object on console, like System.out.println(name); after its initialisation and post its assignment.
I will also suggest you to refer this link (https://books.trinket.io/thinkjava2/chapter7.html#elements) to understand how array are created, initialised and copied etc..
Code with system.out commands (for understanding)
import java.util.Scanner;
public class ReturnArrayExample1 {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
System.out.println("Variable (a) is referring to > " + a);
for (int i = 0; i < 3; i++) {
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr) {
String[] name = new String[3]; // initializing
System.out.println("Variable (name) is referring to > " + name);
boolean run = true;
do {
try {
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if (rawData.isEmpty()) {
System.err.println("Nothing was entered!");
throw new Exception();
} else {
name = rawData.trim().split("[\\s,]+");
System.out.println("Now Variable (name) is referring to > " + name);
run = false;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Input is out of bounds!\nUnsuccessful!");
} catch (Exception e) {
System.err.println("Invalid entry!\nUnsuccessful!");
}
} while (run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
I you want to throw exception when input is more than 3 then there are many ways to do it. One suggestion from #mohamedmoselhy.com is also decent.

Related

How to convert ArrayList<String> to int[] in Java

I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String stringGuess) {
String result = "Miss";
int index = locationCells.indexOf(stringGuess);
if (index >= 0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).

What is supertype?

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//star my method lab
public class Method extends JPanel {
//two array lists that I am going to use.
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public void loadEnglishWords() {
//input my file
String filename = "english.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
//scan all array line by line
while (s.hasNextLine()) {
String line = s.nextLine();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public void loadFrenchWords() {
String filename = "french.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public String lookup(String word){
for (int i = 0; i < english.size();i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r == ("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null,a,"RESULT!",JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
#Override
public void init() {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
//My problem is that everytime I compile this program the error message would be:
"Method.java:88: error: method does not override or implement a method from a supertype
#Override
^
1 error"
//This program is to translate french words to english words using arraylist
I`m using a .txt file for my set of english and french words and have it run through arraylist to translate
//In my program I need to use a JPanel or pop-up box to ask the user to input the word that they wish to translate
//Please note that I am a beginner with Java, please somebody help me and point out on where I got it wrong so I can change it. Thank you so much!
What the error is saying is that in line 88, you are using the #Override to redefine a method named init from parent class JPanel. But because JPanel is what it is (i.e. a part of Java), it does not have init method, you can not redefine it, hence the error. Most likely, you should just remove the #Override, which will mean you want to add a new method instead of redefining it.
Inheritance is a mechanism where you take an existing class and modify it according to your needs. In your case, your class is named Method and it extends (inherits from) JPanel, so JPanel is the supertype of your class.
If you're just beginning, go read and educate yourself on object-oriented concepts. There are many tutorials, including YouTube videos. Happy learning!
Aside from what was previously mentioned, you need to change a few things:
public void init() { should be public static void main(String args[]) {
Then you need to make your methods static, i.e.
public static void loadEnglishWords() {
Also, the arrayLists need to also be static
And one other thing, you should compare with .equals() and not ==
I've re-written your code slightly and now it should work:
static ArrayList<String> english = new ArrayList<>();
static ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public static void loadEnglishWords() {
//input my file
try {
Scanner s = new Scanner(new File("english.txt"));
//scan all array line by line
while (s.hasNextLine()) {
String line = s.next();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public static void loadFrenchWords() {
try {
Scanner s = new Scanner(new File("french.txt"));
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public static String lookup(String word) {
for (int i = 0; i < english.size(); i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public static void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r.equals("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null, a, "RESULT!", JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
public static void main(String args[]) {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}

How do I have a program create its own variables with Java?

I would like to start off by saying that if this is common knowledge, please forgive me and have patience. I am somewhat new to Java.
I am trying to write a program that will store many values of variables in a sort of buffer. I was wondering if there was a way to have the program "create" its own variables, and assign them to values.
Here is an Example of what I am trying to avoid:
package test;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int inputCacheNumber = 0;
//Text File:
String userInputCache1 = null;
String userInputCache2 = null;
String userInputCache3 = null;
String userInputCache4 = null;
//Program
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("User Input: ");
String userInput;
userInput = scan.nextLine();
// This would be in the text file
if (inputCacheNumber == 0) {
userInputCache1 = userInput;
inputCacheNumber++;
System.out.println(userInputCache1);
} else if (inputCacheNumber == 1) {
userInputCache2 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 2) {
userInputCache3 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 3) {
userInputCache4 = userInput;
inputCacheNumber++;
}
// And so on
}
}
}
So just to try to summarize, I would like to know if there is a way for a program to set an unlimited number of user input values to String values. I am wondering if there is a way I can avoid predefining all the variables it may need.
Thanks for reading, and your patience and help!
~Rane
You can use Array List data structure.
The ArrayList class extends AbstractList and implements the List
interface. ArrayList supports dynamic arrays that can grow as needed.
For example:
List<String> userInputCache = new ArrayList<>();
and when you want to add each input into your array like
if (inputCacheNumber == 0) {
userInputCache.add(userInput); // <----- here
inputCacheNumber++;
}
If you want to traverse your array list you can do as follows:
for (int i = 0; i < userInputCache.size(); i++) {
System.out.println(" your user input is " + userInputCache.get(i));
}
or you can use enhanced for loop
for(String st : userInputCache) {
System.out.println("Your user input is " + st);
}
Note: it is better to put your Scanner in your try catch block with resource so you will not be worried if it is close or not at the end.
For example:
try(Scanner input = new Scanner(System.in)) {
/*
**whatever code you have you put here**
Good point for MadProgrammer:
Just beware of it, that's all. A lot of people have multiple stages in their
programs which may require them to create a new Scanner AFTER the try-block
*/
} catch(Exception e) {
}
For more info on ArrayList
http://www.tutorialspoint.com/java/java_arraylist_class.htm

Entering multiple things in to one array in java

I am quite new to java but have a project i need to complete and am stuck on a certain part.
I want to allow the user to enter a route including, start destination, an end destination, and a number of stops. I have been able to do this, but then i want the user to have the ability of being able to add the same things again, to the same array. without deleting the existing route
here is the code i have so far
import java.util.Scanner;
import java.util.Arrays;
public class main {
public static void main(String[] args){
menu();
}
public static void menu(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
inputRoute();
}
}
public static void inputRoute(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
String[] stops = new String[numberOfStops];
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
stops[i-1] = scanner.next();
}
System.out.println(Arrays.toString(stops));
menu();
}
}
however when this runs, if i go back and enter in another route, it will just delete the existing route.
Is there any way of appending the next route to the end of that array or any way of doing this?
thank you
Like crush said. Rather than use a normal array of strings, use an ArrayList<String> object. Or even an ArrayList<String[]> and stash each individual route in there.
First of all you will need to declare the stops array as an instance variable, otherwise you will always be creating a new array whenever you call the method inputRoute().
and then to preserve old entries i can think of two ways-->
--> modify the loop as below...
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
if(stops!=null) //without the if condition it will also append null in the start
stops[i-1]=stops[i-1]+", "+ scanner.next(); // you can you any separator
else
stops[i-1]=scanner.next();
}
--> or you can ArrayList or any other Collection that provides auto increment
Try declaring stops as a global variable. (right below the class line)
Also I would recommend using an ArrayList, List something on those lines
You can't use an array for this (without constantly re-allocating them) as Arrays are fixed in size once created.
Use an ArrayList though and you can add as many items as you like whenever you like.
The easy (and slightly wrong) solution would be to make your array a static array that is defined outside any method. That will get you going (although you will have to make the array big enought.
Other recommendations:
Capatilize your Main class--avoids confusiong (even moreso if you
don't call it main!)
Make your public static void main method do
this: new Main()
Then get rid of all the other statics.
Use a collection instead of an array.
instead of adding each entry into the array separately (which will make EVERYTHING harder for you), create a second class with 3 fields (start, end, stop) and each time you input another record, "new" an instance of the second class, place the three things into the new instance and place that instance on your collection.
It may seem arbitrary and unnecessary right at this minute, but if you have ANY follow-on work to do on this class these things will make your life easier. If any seems confusing or you want to understand why, feel free to ask in the comments.
I think this will help you.
Main file.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
menu();
}
public static void menu(){
List<Route> routeList = new ArrayList<Route>();
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
routeList.add(inputRoute());
}
System.out.println("Complete list of routes is "+routeList);
}
public static Route inputRoute(){
Route route = new Route();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the name of the route");
String name = scanner.next();
route.setName(name);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
route.setStartLocation(startDest);
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
route.setEndLocation(endDest);
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
if(numberOfStops > 0){
route.setStopList(new ArrayList<String>());
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
route.getStopList().add(scanner.next());
}
System.out.println("current entered route is "+route);
menu();
}
return route;
}
}
Route file:
import java.util.List;
public class Route {
String name ;
String startLocation;
String endLocation;
List<String> stopList;
public Route() {
}
public Route(String name, String startLocation, String endLocation, List<String> stopList) {
this.name = name;
this.startLocation = startLocation;
this.endLocation = endLocation;
this.stopList = stopList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartLocation() {
return startLocation;
}
public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}
public String getEndLocation() {
return endLocation;
}
public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}
public List<String> getStopList() {
return stopList;
}
public void setStopList(List<String> stopList) {
this.stopList = stopList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Route route = (Route) o;
if (endLocation != null ? !endLocation.equals(route.endLocation) : route.endLocation != null) return false;
if (name != null ? !name.equals(route.name) : route.name != null) return false;
if (startLocation != null ? !startLocation.equals(route.startLocation) : route.startLocation != null)
return false;
if (stopList != null ? !stopList.equals(route.stopList) : route.stopList != null) return false;
return true;
}
#Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (startLocation != null ? startLocation.hashCode() : 0);
result = 31 * result + (endLocation != null ? endLocation.hashCode() : 0);
result = 31 * result + (stopList != null ? stopList.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Route{" +
"name='" + name + '\'' +
", startLocation='" + startLocation + '\'' +
", endLocation='" + endLocation + '\'' +
", stopList=" + stopList +
'}';
}
}

error: cannot be resolved to a type

import java.util.*;
class AddressBook {
private static final int DEFAULT_SIZE = 25;
private Person[] entry; //getting error - cannot be resolved to a type
public AddressBook() {
this( DEFAULT_SIZE);
}
public AddressBook(int size) {
if (size <= 0) {
throw new IllegalArgumentException("Size must be positive");
}
entry = new Person[size]; // cannot be resolved to a type
System.out.println("array of " + size + " is created");
}
}
import java.util.Scanner;
class TestAddressBook {
public static void main(String args[]) {
AddressBook myBook;
String inputStr;
int size;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.print("array size: " );
inputStr = scanner.next();
if (inputStr.equalsIgnoreCase("stop")) {
break;
}
size = Integer.parseInt(inputStr);
try {
myBook = new AddressBook(size);
}
catch (IllegalArgumentException e) {
}
System.out.println("Exception thrown: size = " + size);
}
}
}
I can't figure out what type I am supposed to use with the array to get everything to work properly.
private Person[] entry; //getting error - cannot be resolved to a type
....
entry = new Person[size]; // cannot be resolved to a type
Where is Person defined? at the very least, adding the following:
class Person {}
will allow it to compile. Otherwise, it doesn't know what you mean when you create Person arrays.
This has nothing to do with arrays (you might want to change the question title). You are either:
Missing the import for the Person class.
Missing the class/package from your build (assuming you're probably using a command line to compile.
The actual error might help.

Categories