我不太清楚这有什么问题,我相信它与范围有关。昨天我遇到了一个问题,即一个字段将自己初始化为零,这是因为我不止一次地回顾了该方法,因此无论调用哪种方法的时间,都会使该类字段保持其值,从而解决该问题。多个实例不能使用相同的变量,变量不能改变
现在我有相反的问题,我需要现场复位,因为另一个对象需要使用它(这是可能的/糟糕的做法?)
下面是代码:
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?什么是最好的方法来解决这个问题?
您是否知道displayInfo始终使用相机,因此它从不使用camera2? – MrP
OMG ...我觉得像这样的工具哈哈。什么是最好的方式让它输出而不必复制代码? – Gibbo
让displayInfo带一个参数:displayInfo(DigitalCamera camera) – MrP