I'm trying to input a number of strings (song names) into an array. The program will then ask the user to name one of songs and tell the user what position that song was placed in the array.
Edit:
Thanks for the help guys. I've set both for loops to 0 and i'm still having trouble.
I'm having various issues with the program. I'm getting the runtime errors of ArrayIndexOutOfBoundsException and NullPointerExeption.
What should I be doing to make it work?.
Thanks in advance to everyone.
Code:
import javax.swing.*; // import the swing library for I/O
class favsongs
{
public static void main (String[] param)
{
music();
System.exit(0);
} // END main
/* ***************************************************
Set up an array containing songs then find one asked for by the user
*/
public static void music()
{
// Declare variables
//
String key =""; //the thing looked for
int result = -1;// the position where the answer is found
String[] songs = new String[5];
// Ask for songs
for (p=0; p<=4; p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
// Ask user for a song
key = JOptionPane.showInputDialog("Name a song and i'll tell you what position you placed it in.");
for (int i=0; i<songs.length; i++)
{
if (songs[i].equals(key))
{
result = i;
}
else // Error message
{
JOptionPane.showMessageDialog(null,"Error!!");
break;
}
}
// Tells user the name of the song and what position in the array it is in
JOptionPane.showMessageDialog(null,"You placed " + key + " in position " + " " + result);
} // END music
} // END class favsongs
ArrayIndexOutOfBoundsExceptionandNullPointerExeptionare runtime-exceptions so you don't get those from the compiler.