我試圖尋找在具有隨機數數組中的int值 這是我到目前爲止有:在數組中搜索一個int
String names[]={"Peter","John","Rudy"};
int number[]=new int[3];
for(int z=0;z<3;z++)
{
number[z]=(int)(1+Math.random()*200);
}
int option=Integer.parseInt(JOptionPane.showInputDialog("choose and option:\n1.names\n2.sorting according to alphabet\n3.search number\n4.J"));
switch(option)
{
case 1:
{
for(int l=0;l<names.length;l++)
{
jTextArea1.append(""+names[l]+"\t"+number[l]+"\n");
}
}
break;
case 2:
{
String temp="";
for(int ii=0;ii<names.length;ii++)
{
for(int j=0;j<names.length;j++)
{
if(names[ii].compareToIgnoreCase(names[j])<0)
{
temp=names[ii];
names[ii]=names[j];
names[j]=temp;
}
}
}
for(int x=0;x<names.length;x++)
{
jTextArea1.append(""+names[x]+"\n");
}
}
break;
case 3:
{
boolean found=false;
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
for(int i=0;i<number.length;i++)
{
if(number[i]==searchvalue)
{
found=true;
}
}
if(found==true)
{
jTextArea1.append("number is found"+"\n");
}
else
{
jTextArea1.append("number is not found"+"\n");
}
}
break;
case 4:
{
for(int q=0;q<names.length;q++)
{
if(names[q].startsWith("J"))
{
jTextArea1.append(names[q]);
}
}
}
}
即使當我鍵入正確的答案吧給我「沒有找到號碼」的信息。我在做什麼都傻眼了。任何幫助將不勝感激。
嘗試打印'searchvalue' ...是否與您輸入的號碼相同? – Nullpointer
另外數字數組定義在哪裏? – RenegadeAndy
這是使用調試器的地方,會有所幫助。雖然你的代碼可以改進,但它基本上沒問題(我運行了它的一個版本來測試)。所以把它放到IDE中,設置一些斷點,並檢查你的變量是否是你期望的。 Searchvalue是你期望的嗎?數字[]的值如何? –