2 baidu 31670843 baidu_31670843 于 2016.04.08 09:59 提问

Java编写的售票系统问题求教

编程初学者,我用Java编写了一个简单的售票系统,但是运行时候报错,希望大牛能帮我看一下!
这是一个User类:

package subwayTicketSellingSystem;
import java.util.Scanner;

public class User
{
private String ticketType;
private Ticket tic;
private TicketMachine machine;
public double money;
public Ticket buyTicket;
public static void main(String[] args)
{
User user1 = new User();
System.out.println("Please choose your ticket type: ");
System.out.println("1: normal ticket");
System.out.println("2: day ticket");
Scanner ticketType = new Scanner(System.in);
String ticType = ticketType.nextLine();
switch(ticType)
{
case "1":
user1.tic = new norTicket();
break;
case "2":
user1.tic = new dayTicket();
}
System.out.println("Your ticket price is: " + user1.tic.calculatePrice());
System.out.println("Please pay for your tickets: ");
Scanner money = new Scanner(System.in);
String userMoney = money.nextLine();
if (user1.machine.collectMoney())
{
System.out.println("Your charge is: " + user1.machine.giveCharge());
user1.machine.printTicket();
}
else System.out.println("Mnoey is not enough, invalid operation.");
}
}
这是一个TicketMachine类:
package subwayTicketSellingSystem;

public class TicketMachine
{
User u1 = new User();
public Ticket Tickets[];
public double getTicketPrice()
{
return u1.buyTicket.calculatePrice();
}
public boolean collectMoney()
{
if ( u1.money >= u1.buyTicket.calculatePrice())
return true;
else return false;
}
public double giveCharge()
{
return u1.money - u1.buyTicket.calculatePrice();
}
public Ticket printTicket()
{
System.out.println("Your original station: ");
return null;
}
}
报错信息:
Exception in thread "main" java.lang.NullPointerException
at subwayTicketSellingSystem.User.main(User.java:31)
十分感谢!

5个回答

strutce
strutce   Ds   Rxr 2016.04.08 10:10

是的user1对象中的参数为null,你debug下,那个值为null

qq_26636247
qq_26636247   2016.04.08 10:14

case "1":
user1.tic = new norTicket();
break;
case "2":
user1.tic = new dayTicket();

user属性赋值要用setTic(),对象属性要有get、set方法的!

u011225629
u011225629   2016.04.08 11:18

String userMoney = money.nextLine();
if (user1.machine.collectMoney())
{
System.out.println("Your charge is: " + user1.machine.giveCharge());
user1.machine.printTicket();
}、
这部分的出现的空指针错误,八成是你的user1为空所以。。。。

theSnai1
theSnai1   2016.04.08 12:57

at subwayTicketSellingSystem.User.main(User.java:31),提示User类的main方法中的user.java文件的31行报错空指针,因为User的属性machine没有进行初始化,Java的默认构造函数会将machine置为null,因而报错空指针。

liuweihong2000
liuweihong2000   2016.04.09 17:38

我专门把你的代码放入了eclipse,可以很明显地看出,machine没有实例化。应该调用 new 来生成对象。
更进一步,象这种 TicketMachine 往往在系统中只有一个,应该采用单例模式。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!