I'm 开发者_Go百科a beginner. I want to read a number a
from the console and then store them in variable to use as passing to a different class (different .java
file).
How do I code the 2 classes?
public class PassedInMethod{
private int a;
public PAssMethod(int a) {
a = a; // TODO: where to get the a?
System.out.println("a was passed in!"+a);
}
}
public class Mainclass {
public static void main( String args[] ) {
Scanner input = new Scanner( System.in );
int a;
System.out.print( "Enter your nember: " );
a = input.nextInt();
PassedInMethod(int a);
}
}
If you want to create an instance of the PassedInMethod
class in which the member variable a
contains the value passed to the constructor.
Try changing
PassedInMethod(int a);
to
PassedInMethod myObj = new PassedInMethod(a);
Also, if you want to update the instance variable to the value of the argument you need to do
this.a = a;
since the argument "hides" the instance varuable.
If you don't want to create an instance, and just invoke a method in a different class, you need to make the method static like this:
public static void PassMethod(int a) {
// ....
}
You could then call the method like this
PassedInMethod.passMethod(a);
PassedInMethod
however is not a very good name for a class, but I'm sure that was just for the sake of the example in the question.
You need to change
PassedInMethod(int a);
To
new PassedInMethod(a);
This looks to be more of what you want. You code had some syntax errors and such.
public class PassedInMethod {
private int a;
public PAssMethod(int a) {
this.a = a;
System.out.println("a was passed in!"+a);
}
}
public class Mainclass {
public static void main( String args[] ) {
Scanner input = new Scanner( System.in );
int a;
System.out.print( "Enter your nember: " );
a = input.nextInt();
PassedInMethod myobj = new PassedInMethod();
myobj.PAssMethod(a);
}
}
精彩评论