我不太确定这有什么问题,我确信它与范围有关。昨天我遇到了一个问题,由于我不止一次地调用该方法,一个字段将自己初始化回零,使一个类字段修复了这个问题,因为它保留了它的值,而不管调用了多少次任何方法。
现在我遇到了相反的问题,我需要重置该字段,因为另一个对象需要使用它(这是可能的/不好的做法吗?)
这是代码:
public class TestDigitalCamera {
static String brand;
static double megaPixels;
static double price;
//create 2 camera instances with the values of the variables tied to the arguments.
static DigitalCamera camera = new DigitalCamera(brand, megaPixels);
static DigitalCamera camera2 = new DigitalCamera(brand, megaPixels);
public static void main(String[] args) {
//no idea what this technique is called, need to look back but I know what it does
//I could use a for loop and reuse the same object over and over(would that even work anyway?) but the task says
//that i require 4 instances, ofc I am just working with 2 atm for simplicity
camera = getInformation(camera);
displayInfo();
camera2 = getInformation(camera2);
displayInfo();
}
//it basically runs this for the camera instance...right? lol
public static DigitalCamera getInformation(DigitalCamera dc){
Scanner userInput = new Scanner(System.in);
//self explanatory
System.out.println("Enter brand: ");
brand = userInput.next();
System.out.println("Enter Mega Pixels: ");
megaPixels = userInput.nextDouble();
//I have another class setup with getters/setters for this, which get used in the next method
dc.setBrand(brand);
dc.setMegaPixels(megaPixels);
return dc;
}
public static void displayInfo(){
//users the getters to pull the values
//the price is calculated using an if statement
System.out.println("Brand: " + camera.getBrand() + "\n"
+ "Megapixels : " + camera.getMegaPixels() + "\n"
+ "Price : $" + camera.getPrice() + "\n");
}
}
这是因为范围吗?该变量可用于任何和所有对象,但它只能用于 1?解决这个问题的最佳方法是什么?