Question

I am trying to pass a value from the main method and set it to a private variable. Here is the main method that's pertinent:

import java.util.*;
public class Experiment{
private static Extension extension=new Extension();

public static void main(String[] ars);{
Scanner input=new Scanner(System.in);

System.out.print("Enter the length: ");
int length=input.nextInt;
extension.messages(length); }
}

and here's what goes with it:

public class Extension{
private int theLength;

public void Extension(int length){
theLength=length; }

public void setLength(int length){
theLength=length; }

public int getLength() {
return theLength }

public void  messages(int length){
System.out.println("theLength: "+theLength);
System.out.println("Length: "+getLength(); }
}

I added the extra display because I wanted to see if the value was getting passed on correctly. When I run it, I realize that it's not; both theLength and length are set to zero despite having input different numbers. Can anyone see what I'm doing wrong? I would sincerely appreciate a thorough answer (since I am just starting out).

Was it helpful?

Solution

You are not setting the private variable length. You should call the setLength(int length) method.

change to this

System.out.print("Enter the length: ");
int length=input.nextInt;
extension.setLength(length); // this will set the private variable
extension.messages(length);

OTHER TIPS

This is a lesson in encapsulation. Your issue, as @salihrkc said, is that you're never actually setting the length variable which exists in your "Extension" object. If you try to print "length" as passed in to your object, you'll see it's getting there just fine.

You act on your object using the dot operator (e.g. extension.messages(length);, to call the messages method). The key points you should be realizing is that you cannot set the objects length by just doing extension.theLength = length;. This is because of the private modifier. Instead you should be using the "getter" and "setter" methods. These functions exist within your object and therefore access to the private variables, so you can do something like extension.setLength(length); and System.out.println(extension.getLength());

Check out the two sources I linked, they'll help.

Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top