baidu_31670843
baidu_31670843
采纳率0%
2016-04-08 01:59 阅读 1.8k

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 丵鹰 2016-04-08 02:10

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

    点赞 评论 复制链接分享
  • qq_26636247 qq_26636247 2016-04-08 02:14

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

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

    点赞 评论 复制链接分享
  • u011225629 君莫傲 2016-04-08 03: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 04:57

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

    点赞 评论 复制链接分享
  • liuweihong2000 liuweihong2000 2016-04-09 09:38

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

    点赞 评论 复制链接分享

相关推荐