Note that there are some explanatory texts on larger screens.

plurals
  1. POmultiple instance can't use the same variable, variable not changing
    primarykey
    data
    text
    <p>I am not quite sure what is wrong with this, I am sure it has to do with the scope. Yesterday I had an issue where a field would initialize itself back to zero due to me recalling the method more than once, making a class field fixed this as it retained it's value regardless of how many time any method is called.</p> <p>Now I have the opposite problem, I need the field to reset because another object needs to use it(is this possible/bad practice?)</p> <p>Here is the code:</p> <pre><code>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"); } } </code></pre> <p>Is this due to the scope? the variable is use-able for any and all objects but it may only be used for 1? What's the best way to approach this? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload