我有一个关于静态与非静态方法的菜鸟问题。 在这个例子中,我解析了数据,并希望将其写入我的数据库。只要我声明方法getData()是静态的,我就做得很好。但是现在当我调用Database.insert(x,y,z)时,静态非静态错误就会发挥作用。我不能围绕问题解决我如何解决这个问题的想法。
任何人都可以向我解释,我如何将这些变量写入我的数据库?你的帮助很受重视,并将帮助我推进java。
编辑:
错误消息说:
Cannot make a static reference to the non-static method insert(String, String, String, String) from the type Database
代码:
package org.jsoup.examples;
import java.io.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import java.io.IOException;
/**
* Example program to list links from a URL.
*/
public class parseEasy {
String companyName = "Platzhalter";
String jobTitle = "Platzhalter";
String location = "Platzhalter";
String timeAdded = "Platzhalter";
public static void main(String[] args) throws IOException
{
Database connect = new Database();
connect.OpenConnectionDB();
getData();
connect.closeConnectionDB();
}
// FIRMENNAME
public static void getData() throws IOException
{
int count = 0;
Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/keywords_SOA.txt"), "utf-8");
Elements elements = document.select(".joblisting");
for (Element element : elements)
{
// Counter for Number of Elements returned
count++;
// Parse Data into Elements
Elements jobTitleElement = element.select(".job_title span");
Elements companyNameElement = element.select(".company_name span[itemprop=name]");
Elements locationElement = element.select(".locality span[itemprop=addressLocality]");
Elements dateElement = element.select(".job_date_added [datetime]");
// Strip Data from unnecessary tags
String companyName = companyNameElement.text();
String jobTitle = jobTitleElement.text();
String location = locationElement.text();
String timeAdded = dateElement.text();
Database.insert(companyName, jobTitle, timeAdded, location);
// Test output
System.out.println("Firma:\t"+ companyName + "\t" + jobTitle + "\t in:\t" + location + " \t Erstellt am \t" + timeAdded + "\t. Eintrag Nummer:\t" + count);
}
}
/* public void writeDB(String a,String b,String c,String d){
Database.insert(a, b, c, d);
}
String getcompanyName(){
return companyName;
}
String getjobTitle(){
return jobTitle; }
String gettimeAdded(){
return timeAdded; }
String getlocation(){
return location; }
*/
}
答案 0 :(得分:1)
Static
和Non-Static
也有2个,也许是更好的名字。
Static
也称为Class-Level
,Non-Static
为Instance-Level
示例:
class SomeClass {
static void staticPrint() {
// ^^^^^^^^^^^ static
System.out.println("Hello from static");
}
void instancePrint() {
// ^^^^ not static
System.out.println("Hello from non-static");
}
}
所以这两种方法的区别在于:
SomeClass obj = new SomeClass();
SomeClass.staticPrint(); // prints "Hello from static"
SomeClass.instancePrint(); // throws an error
obj.staticPrint(); // throws an error
obj.instancePrint(); // prints "Hello from non-static"
那就是它。这是静态和非静态之间的区别
一个直接在课堂上工作,另一个在你new