gpt4 book ai didi

java - 无法在java中调用方法

转载 作者:行者123 更新时间:2023-11-30 10:54:37 25 4
gpt4 key购买 nike

我有一个非常愚蠢的问题,让我很头疼。

我定义了一个方法来搜索 ArrayList 以查找邮政编码:

    public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(0);
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
else
aZip = null; }
return aZip; }

...但是,我不能终生称之为它。每次我调用它时,它都会给我“找不到符号”错误,无论我使用什么对象或输入什么参数。

整个程序到此为止(想不通才算完):

import java.util.*;
import java.io.*;
import java.lang.Math;
public class ZipCodeDatabase {
//Field
private ArrayList<ZipCode> zips;

//Constructor
public ZipCodeDatabase () {
zips = new ArrayList<ZipCode> ();
}

//Mutator Method
public void readZipCodeData(String filename) {
Scanner inFS = null;
FileInputStream fileByteStream = null;
try{
// open the File and set delimiters
fileByteStream = new FileInputStream("zipcodes.txt");
inFS = new Scanner(fileByteStream);
inFS.useDelimiter("[,\r\n]+");
// continue while there is more data to read
while(inFS.hasNext()) {
//read in all input
int aZip = inFS.nextInt();
String aCity = inFS.next();
String aState = inFS.next();
double aLat = inFS.nextDouble();
double aLon = inFS.nextDouble();
//Create and add new zipcode
ZipCode newZip = new ZipCode(aZip, aCity, aState, aLat, aLon);
zips.add(newZip);
}
fileByteStream.close();
// Could not find file
}catch(FileNotFoundException error1) {
System.out.println("Failed to read the data file: " + filename);
// error while reading the file
}catch(IOException error2) {
System.out.println("Oops! Error related to: " + filename);
}
}

//Accessor Methods
public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(0);
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
else
aZip = null;
}
return aZip;
}
public int distance(int zip1, int zip2) {
int dist = 0;
double p1 = 0.0;
double p2 = 0.0;
double p3 = 0.0;
if(zips.findZip(zip1) == null || zips.findZip(zip2) == null)
dist = -1;
...

错误本身是:

cannot find symbol - Method findZip(int)

You are using a symbol here which has not been declared in any visible scope.

使用 ZipCodeDatabase.findZip(int); 会出现以下编译器错误:

non-static method findZip(int) cannot be referenced from a static context

You are trying to reference an instance field or instance method from a static method.

我目前正在解决这个问题,如有需要,请返回更多更新。感谢您提供的所有帮助。


ZipCode 本身并没有真正解决这个问题,它只是一组用于 zips 的设置和获取方法。

最佳答案

问题出在这一行:

if(zips.findZip(zip1) == null || zips.findZip(zip2) == null)

在类的顶部,我们找到zips 的声明,即

private ArrayList<ZipCode> zips;

这是个问题,因为您的findZip 方法在ZipCodeDatabase 类中,而不是在ArrayList 中。由于该调用是从 ZipCodeDatabase 的非静态方法内部发生的,因此您可以简单地删除调用它的对象。

if(findZip(zip1) == null || findZip(zip2) == null)

这相当于使用

if(this.findZip(zip1) == null || this.findZip(zip2) == null)

它调用 ZipCodeDatabase 类的当前实例上的方法。

关于java - 无法在java中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595722/

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