gpt4 book ai didi

java - 多个实例不能使用同一个变量,变量不会改变

转载 作者:行者123 更新时间:2023-11-30 04:15:24 25 4
gpt4 key购买 nike

我不太确定这有什么问题,我确信它与范围有关。昨天,我遇到了一个问题,由于我多次调用该方法,字段会将自身初始化回零,从而使类字段修复了此问题,因为无论调用任何方法多少次,它都保留其值。

现在我遇到了相反的问题,我需要重置该字段,因为另一个对象需要使用它(这可能/不好的做法吗?)

这是代码:

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?解决这个问题的最佳方法是什么?

最佳答案

您有以下代码:

camera = getInformation(camera);
displayInfo();
camera2 = getInformation(camera2);
displayInfo();

这里,您的方法 displayInfo() 在调用时并没有真正从 camera 对象获取任何参数和打印信息。尽管您在第二次调用 getInformation 时获取了 camera2 对象的引用,但您并没有真正打印它。

您可以像这样声明displayInfo:

public static void displayInfo(DigitalCamera camera) {
//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");
}

关于java - 多个实例不能使用同一个变量,变量不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18530219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com