Sign In | Register Now About Bytes | Help | Site Map
Connecting Tech Pros Worldwide

Arrays

Question posted by: phatcyndy (Newbie) on May 15th, 2008 08:37 AM
Hi
how do i print array contents my code is as follows

import java.util.*;

public class Question1
{
private int[]numbers=new int[19];
private int option;
private int MAX=20;
private int num;
private int count;
public static void main(String[]args)
{
Question1 a= new Question1();
a.menu();
}
public void menu()
{

while(option!=7)
{
System.out.println(" Please select an option");
System.out.println("1. to store number");
System.out.println("2. to print ");
System.out.println("3. to search ");
System.out.println("4. to remove ");
System.out.println("5. to set ");
System.out.println("6. to calculate average ");
System.out.println("7. to quit ");
System.out.println(" option: ");
Scanner scan=new Scanner(System.in);
option=scan.nextInt();
if (option==7)
{
System.exit(0);
}else if (option==1)
{
enterNumber();
}

else if (option==2)
{
printNumbers();
}
//else if(option==3)
// {
// a.searchNumber();
// }
// else if(option==4)
// {
// // a.removeNumber();
// }else if (option==5)
// {
// // a.setNumber
// }else if(option==6)
// {
// // a.calcuate();
// }


}

}

public void enterNumber()
{
while (count!= MAX)
{
System.out.println("Enter intergers between 1 and 20 or (99 to quit)");
Scanner scan=new Scanner(System.in);
int num=scan.nextInt();
count++ ;
if (num==99)
{
System.out.println("Program quit");
System.exit(0);
}else if(numbers .length >MAX)
{
System.err.println("Too much data!!!");
System.exit(0);
}

}
}
// having trouble here
public void printNumbers()
{
for(int a =1;a<=MAX;a++)
{
if(num>0)
{
System.out.println (numbers[a +1]);
}
return 0;
}
}


// public void searchNumber()
//
// {
//
// System.out.println("Please enter a specified number ");
// Scanner scan= new Scanner(System.in);
// int num1=scan.nextInt();
//
// if (numbers[num1]== num1)
// {
// System.out.println("The number " + num1 + " is found ");
// return num1;
//
// }else
// System.out.println("The number " + num1 +" is not found");
// return -1;
// }
}
JosAH's Avatar
JosAH
Chief Editor
7,787 Posts
May 15th, 2008
09:33 AM
#2

Re: Arrays
You array indexing technique is goofy: you have an array with 19 elements (see
your own code). Array indexes start at zero (0) in Java so the valid index values
are 0, 1, 2, 3 ... 17, 18. Your code will cause an IndexOutOfBoundsException
at several places.

You can print the contents of an array in an extremely lazy way: check the
methods in the Arrays utility class. You don't even need to craft a loop
for it.

kind regards,

Jos

Reply
Reply
Not the answer you were looking for? Post your question . . .
190,179 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Latest Articles: Read & Comment
Top Java Forum Contributors