gpt4 book ai didi

java - 我声明的数组大小是否与我的搜索有关?

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:28 25 4
gpt4 key购买 nike

我有一个程序利用 swing GUI 和新的排序算法和搜索。我的排序工作正常,但是当尝试搜索数字时,我让它给出一条消息,无论是否已找到它。然而,当数字存在时,它说它找到了,而是说它没有找到。而且由于某种原因,它只说在索引 4 处找到了 0。

static int Numbers[]=new int[0];

private static class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//get data
String data = txtInput.getText();

//parse for numerical value
int numGenerate = Integer.parseInt(data);
int Numbers[]=new int[numGenerate];
String command = e.getActionCommand();
if (command.equals("Sort"))
{

String unSortedData="";

//ouput unsoted data
for (int x=0;x<=Numbers.length-1;x++)
{
Numbers[x]=(int)(Math.random()*2001)-1000;
unSortedData+=(Numbers[x]+",");

}
txtUnsorted.setText(unSortedData);




if (btnQuickSort.isSelected())
{
QuickSort(Numbers,0,Numbers.length-1);
}
if (btnMergeSort.isSelected())
{
MergeSort(Numbers,0,Numbers.length-1);
}
if (btnInsertionSort.isSelected())
{
InsertionSort(Numbers);
}
if (btnSelectionSort.isSelected())
{
SelectionSort(Numbers);
}
if (btnShellSort.isSelected())
{
ShellSort(Numbers);
}
if (btnShakerSort.isSelected())
{
ShakerSort(Numbers);
}
generated=true;




}
if (command.equals("Search"))
{
//get data
String data2 = txtSearch.getText();
//parse for numerical value
int FindNum = Integer.parseInt(data2);

if (generated==true)
{
int counter=0;

for (int x=0;x<Numbers.length;x++)
{
if (Numbers[x]==FindNum)
{
lblSearch.setText("Status: Found "+ FindNum+ "at index "+ counter );
}
counter++;
}

}
else
{

lblSearch.setText("Status:Error! Enter or sort a number");
}
}



}
}

最佳答案

目前,如果运行“搜索”组件,您只会用随机数填充数组。我建议将生成和两个操作分成单独的方法:

private int[] randomNumbers(int size) {
Random random = new Random();
int[] numbers = new int[size];
for (int i = 0; i < numbers.length; i++)
numbers[i] = random.nextInt(2000) - 1000;
unsortedData = Arrays.toString(numbers);
}

public void actionPerformed(ActionEvent e) {
int[] numbers = randomNumbers(Integer.valueOf(txtInput.getText());
switch(e.getActionCommand()) {
case "sort":
...
break;
case "search":
...
break;
}
}

请注意,有一种更简单的方法来获取随机整数数组:

int[] numbers = random.ints(size, -2000, 2000).toArray();

但我假设您还没有使用流。

关于java - 我声明的数组大小是否与我的搜索有关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com