我进入Java课程的第一个介绍已经有5个星期,而且我被困住了。我应该做一个库存计划。它应该让用户输入几个东西,包括名称,产品ID,单位和价格。然后它应该输出包括总值的信息,即单位*价格。
我创建了一个类,构建了一个构造函数,并创建了一个toString方法,但似乎这些东西没有被调用到main方法中,并且对于我的生活我无法弄清楚我是什么丢失。
我不知道如何让这些东西真正起作用。我一直在寻找几个小时寻找我所缺少的东西,我想我需要一个全新的视角。
public class Inventoryprogram {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
DVD dvd;
while (!finish){
Scanner input = new Scanner(System.in);
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
}
else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.println("DVD: " + dvdName);
System.out.println("ID: " + itemNum);
System.out.println("Units: " + quantity);
}
}
}
public class DVD {
private String name;
private int id;
private int items;
private double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
dvdName = name;
itemNum = id;
quantity = items;
price = cost;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
public String toString(String getName, int getID, int getItems, double getCost, double getInventoryValue) {
return "DVD Name: " + getName +
"ID: " + getID +
"Items: " + getItems +
"Cost: " + getCost +
"Total Value: " +getInventoryValue;
}
}
}
答案 0 :(得分:0)
在Java中,只有在使用new
关键字时才会完全调用构造函数。如果你想制作一个DVD对象,你需要在代码中的某个地方放置new DVD
,然后是一个参数列表,它将构成构造函数的参数。
答案 1 :(得分:0)
要使用上面的类创建新实例,您需要编写以下内容:
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
任何时候你想要使用对象的实例而不是静态方法(大多数时候都是这样),这就是你要做的事情。这就像调用类中的方法一样,除了您通过'new
关键字调用构造函数来创建新实例。
编辑 以发表评论 如果您收到错误,指出您的值未初始化,并且将内部类声明为静态解析它,则意味着您在没有创建外部类的实例的情况下引用内部类。
有关如何使用外部类的实例实例化内部类的语法,您需要:
OuterClass.InnerClass innr = new OuterClass().new InnerClass();
那说 - 在大多数情况下(不是全部,但几乎所有情况)如果你从另一个类引用一个内部类,你最好将内部类放入它自己独立的完整类中。拥有.java文件。