循环,获取/设置方法,以及多个类,哦,我的

时间:2013-09-06 01:32:51

标签: java loops constructor getter-setter

我真的在使用get / set方法苦苦挣扎。我理解基本概念 - 首先设置值然后检索它。我发现用我已经学过的最小概念找到有关它的信息相当困难。我是第6章或我的第一个Java和编程课程,它都在线。我创建了一些使用set / get方法的其他类,但那些似乎并不适合这个项目。

public class Purchase{
   int inv;
   double sale;
   double tax;
   double taxAmount = 0.05;

public int getInv()
{
   return inv;
}
public void setInv(int inv)
{
   inv = inv;
}

public void setSale(double s)
{
   sale = s;
   tax = sale * taxAmount;
}
public double getSale()
{
   return sale;
}

//display
public void display()
{
System.out.println("Invoice number: " + getInv() + "\nSale amount: $" + getSale() + "\nTax: $" + tax + "\nTotal: $" + (tax + sale));
}
}

import java.util.Scanner;
public class CreatePurchase{
public static void main(String[] args)
{
   Purchase one = new Purchase();

   Scanner input = new Scanner(System.in);
   do
   {
   System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000.  ");
   inv = input.nextInt();
   one.setInv(inv);
   }
   while(inv < 1000 && inv > 8000);
   {
   System.out.println("Please enter the amount of your sale.  ");
   sale = input.nextInt();
   }
}
}

CreatePurchase类没有完成,但我编译它并在每次出现时为每个变量获取以下内容:

CreatePurchase.java:16: error: cannot find symbol
      inv = input.nextInt();
      ^

我的理解是创建了一个默认构造函数,所以我没有添加一个,而是在CreatePurchase中调用它。 有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您未能在任何地方声明变量inv,例如......

public static void main(String[] args) {
    Purchase one = new Purchase();

    // !! Variable must be declared before it can be used !! //
    int inv = 0;
    Scanner input = new Scanner(System.in);
    do {
        System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000.  ");
        inv = input.nextInt();
        one.setInv(inv);
    } while (inv < 1000 && inv > 8000);
    {
        System.out.println("Please enter the amount of your sale.  ");
        // This will be your next problem...
        sale = input.nextInt();
    }
}

你的Purchase课程也会遇到问题......

以下方法实质上是将inv的值赋予自身,这在此上下文中毫无意义......

public void setInv(int inv)
{
    inv = inv;
}

相反,您应该分配给Purchase类的inv变量的实例......

public void setInv(int inv)
{
    this.inv = inv;
}

答案 1 :(得分:1)

你至少有两个问题。首先,您可以创建一个与另一个更大容器(范围)中的变量同名的新变量。在这种情况下,新变量“隐藏”或“遮蔽”外部变量。在setInv方法中,当您说inv = inv时,两个 inv都会引用最里面的变量,即方法签名中的变量。要将参数保存到类的字段,您需要指定外部invthis.inv = inv;

CreatePurchase班级中,您没有定义任何inv; Purchase中有一个,但那里有,而不是这里。您只需在int inv;之后立即声明Purchase one

根据这两个错误,我建议您阅读一篇关于Java中变量范围的文章或教程,以了解哪些变量可以访问的规则。

答案 2 :(得分:1)

在此步骤中,您尚未在inv方法中声明变量main inv = input.nextInt(); 将您的计划更改为以下

int inv = 0;
 Scanner input = new Scanner(System.in);
   do
   {
   System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000.  ");
   inv = input.nextInt();
   if(inv >1000 & inv <8000)
        one.setInv(inv);//add to one variable only if its correct,otherwise ignore it
   }
   while(inv < 1000 && inv > 8000);