【发布时间】:2014-10-23 02:38:38
【问题描述】:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class n00686349
{
public static void main(String args [])throws FileNotFoundException
{
String control;
FileInputStream fis = new FileInputStream("C:/Users/Steven Fowler/Desktop/data.txt");
Scanner scanner = new Scanner(fis);
vehicle one = new vehicle();
while(scanner.hasNextLine())
{
control = scanner.nextLine();
if (control.equals("vehicle") == true)
{
new vehicle();
one.setOwner(control);
}
else if (control.equals("car") == true)
{
System.out.println("You doing alright");
}
else if (control.equals("truck") == true)
{
System.out.println("You doing alright");
}
else if (control.equals("bicycle") == true)
{
System.out.println("You doing alright");
}
else if (control.equals("american car") == true)
{
System.out.println("You doing alright");
}
else if (control.equals("foreign car") == true)
{
}
}
scanner.close();
}
public class vehicle
{
private String ownersName;
private String address;
private String phone;
private String email;
public vehicle()
{
this.ownersName = ("none");
this.address = ("none");
this.phone = ("none");
this.email = ("none");
}
public void setOwner (String ownersName)
{
this.ownersName = ownersName;
}
public void setAddress (String address)
{
this.address = address;
}
public void setPhone (String phone)
{
this.phone = phone;
}
public void setEmail (String email)
{
this.email = email;
}
public String ownersName()
{
return ownersName;
}
public String address ()
{
return address;
}
public String phone ()
{
return phone;
}
public String email()
{
return email;
}
}
class car extends vehicle
{
private boolean convertible;
private String color;
public car()
{
convertible = false;
color = ("none");
}
public void setConvertible (boolean convertible)
{
this.convertible = convertible;
}
public void setColor (String color)
{
this.color = color;
}
public boolean convertible ()
{
return convertible;
}
public String color ()
{
return color;
}
}
上面是我的一个类的代码,它逐行从文件中读取输入并将信息处理成一个对象(尚未完成仍在构建)。我理解为什么您通常会收到此错误消息。如果不先创建对象,分配对对象的引用,然后调用对象方法,则无法访问实例方法。每当我尝试创建新对象时,都会在第 16 行和第 23 行弹出此错误。所以我一直在玩这个,如果我把类车改成静态的,它就可以工作。所以我的问题是:将类更改为静态更改所有变量静态,这就是它起作用的原因吗?这意味着什么?(使创建实例的类静态)并且我在我的车辆类中使用 this.variable 然后尝试扩展该类导致此问题?我对使用 this 关键字不是很熟悉。
谢谢
【问题讨论】:
-
更新了此代码以使类取消嵌套。我们需要覆盖对象中的 tostring 方法,尝试执行此操作似乎非常麻烦,我不确定我的代码当前的方式是否可行。
标签: java static compiler-errors non-static