- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我问这个问题的原因是因为我仍然遇到空指针异常,即使我确定没有问题,但像往常一样,我可能犯了一些大错误。
讲座幻灯片是这样说的
使用变量存储数组元素序列的起始索引和长度,如果有的话,这些元素必须包含 Mike 的条目。
设置start-index为0,length为数组长度。
当长度大于1
a) 将 Mike 与中间元素中的名字进行比较(在 start_index + length/2)
b) 如果它更早,则将长度设置为 length/2 并保持 start-index 不变。
c) 如果晚于或等于,则将 length/2 添加到 start-index 并从长度中减去 length/2
这是我的代码(这是我正在更改的电话簿记录中的搜索方法)。补充一下,该程序加载了一个文本文件,该文件在不同的行上以下列格式存储名称和数字
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/
这段代码在 Java 中的等价物是什么?我放了一部分,我对 I/O 部分感兴趣: int fd = open(FILE_NAME, O_WRONLY); int ret = 0; if (fd =
我正在尝试将维度为 d1,d2,d3 的张量 M[a1,a2,a3] reshape 为维度为 d2, d1*d3 的矩阵 M[a2,a1*a3]。我试过 M.reshape(d2,d1*d3) 但是
我是一名优秀的程序员,十分优秀!