在Java中存储和访问字符串(使用数组)
问题描述:
我试图向数组中输入一些字符串(歌曲名称)。然后该程序将要求用户命名一首歌曲,并告诉用户该歌曲放置在该阵列中的位置。在Java中存储和访问字符串(使用数组)
编辑:
感谢您的帮助球员。我已经将循环设置为0,并且仍然有问题。 我遇到了该计划的各种问题。我得到运行时错误ArrayIndexOutOfBoundsException
和NullPointerExeption
。
我该怎么做才能使它工作?
在此先感谢大家。
代码:
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++)
注意,它从1开始。所以songs[0]
仍将有null
它的默认值。现在看看如何使用数组:
for (int i=0; i<songs.length; i++)
{
if (songs[p].equals(key))
不仅是你想,当我想你的意思i
使用p
在这里,但无论是方式将失败。使用p
将访问songs[5]
,这是超出界限的,并且使用i
将在songs[0]
上调用equals
,其为空。
希望这足以让你走。其他几点:
- “你对不起,什么?”提示符在循环中。你的意思是?
- 你应该看一下Java命名约定,既可以用于大写,也可以给你的方法更有意义的名称
- 你应该尝试在尽可能小的范围内声明变量。如果您将其作为
for
循环的一部分进行声明,您将不会错误地在错误的地方使用p
。
答
// Ask for songs
for (p=1; p<=4; p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
这将使歌曲[0]初始化。当你稍后尝试使用它时,你会得到一个NullPointerException。
答
首先,您的循环将歌曲放入从1开始,尝试设置p = 0,数组从零到长度-1。试试这个,然后看看它是否修复该问题
答
你的问题似乎是在这里:
for (p=1; p<=4; p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
在Java中,数组的位置从0开始,并在[arrayLength]结束 - 1。
否则像这样应该解决您的问题:从Oracle
for (p=0; p < song.length(); p++)
{
songs[p]=JOptionPane.showInputDialog("Song "+ p + "?");
}
This教程应该帮助您开始。您可能还想看看ArrayList类,这将允许您动态地添加项目到您的列表中,如this简单教程中所示。
'ArrayIndexOutOfBoundsException'和'NullPointerExeption'是__runtime-exceptions__,所以你不会从编译器那里得到这些。 –