我试图创造条件
但是当我尝试运行它时,它会强制所有字段为0,即使我为变量设置了正确的值:
Please type your invoice number: ...1111
What month is the balance due?(Choose from 1-12)... 1
What day is the balance due?(Choose from 1-31).... 12
What year is the balance due? (Choose from 2011-2017) ....2011
Your invoice number is 0 and your balance due is on 0/0/0.
public class Invoice
{
private int inNum;
private double balDue;
private int m;
private int d;
private int yy;
public Invoice ()
{
super();
setInNum(inNum);
getInNum();
setBalDue(balDue);
setM(m);
setD(d);
setYy(yy);
}
public int getInNum ()
{
return inNum;
}
public void setInNum (int inNum)
{
if (inNum < 1000)
this.inNum = 0;
else
this.inNum = inNum;
}
public double getBalDue ()
{
return balDue;
}
public void setBalDue (double balDue)
{
this.balDue = balDue;
}
public int getM ()
{
return m;
}
public void setM (int m)
{
if (m < 1 || m > 12)
this.m = 0;
else
this.m = m;
}
public int getD ()
{
return d;
}
public void setD (int d)
{
if (d < 1 || d > 31)
this.d = 0;
else
this.d = d;
}
public int getYy ()
{
return yy;
}
public void setYy (int yy)
{
if (yy < 2011 || yy > 2017)
this.m = 0;
else
this.yy = yy;
}
public void displayInfo ()
{
int inNum;
int m, d, yy;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
inNum = keyboard.nextInt();
System.out
.print("What month is the balance due?(Choose from 1-12) ");
m = keyboard.nextInt();
System.out
.print("What day is the balance due?(Choose from 1-31) ");
d = keyboard.nextInt();
System.out
.print("What year is the balance due? (Choose from 2011-2017) ");
yy = keyboard.nextInt();
System.out.println("Your invoice number is " + getInNum()
+ " and your balance due is on " + getM() + "/" + getD()
+ "/" + getYy() + ".");
}
public static void main (String[] args)
{
Invoice invoice = new Invoice();
invoice.displayInfo();
}
}
答案 0 :(得分:2)
这是失败的,因为您在调用所有setter方法后调用了displayInfo
。它需要先发生,否则制定者无所事事。
我认为在构造函数中调用这些setter方法是错误的。一旦你有了需要传递给它的值,你需要调用每一个。
因此,您输入的每个值都可能有一个局部变量,然后将其传递给setter
int invoiceNumber = keyboard.nextInt();
setInNumber(invoiceNumber);
所有其他领域的等等。
答案 1 :(得分:1)
你为这个班制作了所有那些漂亮的制定者并且没有使用它们!
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
setInNum(keyboard.nextInt());
System.out.print("What month is the balance due?(Choose from 1-12) ");
setM(keyboard.nextInt());
System.out.print("What day is the balance due?(Choose from 1-31) ");
setD(keyboard.nextInt());
System.out.print("What year is the balance due? (Choose from 2011-2017) ");
setY(keyboard.nextInt());
System.out.println("Your invoice number is " + getInNum() + " and your balance due is on " + getM() + "/" + getD() + "/" + getYy() + ".");