
Untitled
By: a guest on
May 20th, 2012 | syntax:
None | size: 1.63 KB | hits: 16 | expires: Never
Storing and accessing strings in Java (by using arrays)
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
for (p=1; p<=4; p++)
for (int i=0; i<songs.length; i++)
{
if (songs[p].equals(key))
// Ask for songs
for (p=1; p<=4; p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
for (p=1; p<=4; p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
for (p=0; p < song.length(); p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}