-1

Im having a problem. when i write for example "18" in the console, it just prints "0". I also want to know how i am able to print all the instance variables when i create a new car object. Thanks a lot.

public class mad { 

  public static void main(String[] args) {
        java.util.Scanner tastatur = new java.util.Scanner(System.in);
        int answer = tastatur.nextInt();

        car carA = new car();
        carA.createCar(answer);

        System.out.println(carA.number);    
        }
  }

  class car {
    int number;

    void createCar(int n) {
        n = number;
  }
}
TedTrippin
  • 3,525
  • 5
  • 28
  • 46
Kondifaxe
  • 9
  • 2

4 Answers4

3

You wrote "n = number" instead of "number = n"

Should be this:

void createCar(int n) {
    this.number = n;
}

For printing all instance variables, see this: printing all variables

Jamal H
  • 934
  • 7
  • 23
0

In constructor line n = number; should be number = n;. You are getting 0 because instance variables are initialized bt 0 or equivalent by default.
To print all variables you must have to define a function to do so. Best way is to override toString() method of Object class.

cse
  • 4,066
  • 2
  • 20
  • 37
0

In your car class, you're currently doing this:

  int number;
  void createCar(int n) {
    n = number; // you're assigning n to the value of number
  }

Switch those around so it reads:

  int number;
  void createCar(int n) {
    this.number = n; // now you're assigning number to the value of n
  }
shmosel
  • 49,289
  • 6
  • 73
  • 138
Will Estes
  • 63
  • 10
0

Your assignment in the class car is the opposite of what you wanted to do. You're assigning the field number (which is always 0) to the parameter n. What you wanted to do is assigning the parameter n to the field number. So the solution is to replace

n = number;

with

number = n;

By the way: By convention class names should start with a capital letter.

Björn Zurmaar
  • 826
  • 1
  • 9
  • 22