gpt4 book ai didi

java - 我的代码是否遵循了适当的逻辑

转载 作者:行者123 更新时间:2023-11-29 04:03:57 26 4
gpt4 key购买 nike

我问这个问题的原因是因为我仍然遇到空指针异常,即使我确定没有问题,但像往常一样,我可能犯了一些大错误。

讲座幻灯片是这样说的

  1. 使用变量存储数组元素序列的起始索引和长度,如果有的话,这些元素必须包含 Mike 的条目。

  2. 设置start-index为0,length为数组长度。

  3. 当长度大于1

a) 将 Mike 与中间元素中的名字进行比较(在 start_index + length/2)

b) 如果它更早,则将长度设置为 length/2 并保持 start-index 不变。

c) 如果晚于或等于,则将 length/2 添加到 start-index 并从长度中减去 length/2

  1. 长度现在是 1,所以它必须是 Mike 的条目,如果他有一个。

这是我的代码(这是我正在更改的电话簿记录中的搜索方法)。补充一下,该程序加载了一个文本文件,该文件在不同的行上以下列格式存储名称和数字

258132 亚当斯,亚伦

199644 亚当斯,算盘

567480 亚当斯,亚伯拉罕

810323 亚当斯,亚当

444601 亚当斯,阿德拉德

/**
* Write a description of the class Record here.
*
* @author John Bovey
* @version 29 September 2009
*/
public class Record
{
private String name;
private String number;

public Record(String name, String number)
{
this.name = name;
this.number = number;
}

public String getName()
{
return name;
}

public String getNumber()
{
return number;
}

}

import java.io.*;
/**
* @author John Bovey
* @version 29 September 2009
*/
public class PhoneBook
{
static final int MAX_RECORDS = 50000;
private Record list[];
private int length;

/**
* Constructor for objects of class PhoneBook
*/
public PhoneBook(String file) throws FileNotFoundException
{
list = new Record[MAX_RECORDS];
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String s = br.readLine();
length = 0;
while (s != null) {
String[] args = s.split(" ", 2);
list[length] = new Record(args[1], args[0]);
s = br.readLine();
length++;
}
}
catch (IOException e) {
}
}

**/**
* Look a name and return the number or null if there is no match
*/
public String search (String name)
{
int startIndex = 0;
int length = list.length;

while(length > 1){

if(name.compareToIgnoreCase(list[startIndex + (length / 2)].getName()) > 0) {
length = length / 2;
}
else{
startIndex = startIndex + (length / 2);
length = length - (length / 2);
}
}

return list[startIndex + (length / 2)].getNumber();
}**


/**
* Test the search method by looking up each name in turn
*/
public void testSearch()
{
for (int i = 0; i < length; i++) {
String name = list[i].getName();
String num_correct = list[i].getNumber();
String num_search = search(name);

if (!(num_correct.equals(num_search))) {
System.out.printf("Failed for %s - search returned %s instead of %s\n", name, num_search, num_correct);
return;
}
}
System.out.println("Ok.");
}


}

最佳答案

另一件事:永远不要吞下这样的异常:

catch (IOException e) {
}

每当您的代码中出现 IOException 时,您都不会知道它,因为您没有对它执行任何操作。正因为如此,错误很难追踪,因为它就像您的代码行为正确一样(毕竟您没有看到错误)。

至少打印一个堆栈跟踪:

catch (IOException e) {
e.printStackTrace();
}

在这种情况下,当 IOException 发生时,您会在控制台上看到一些错误。

关于java - 我的代码是否遵循了适当的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1542398/

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