This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
There are two classes
first class is
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
public class Hieracrhy
{
ArrayList<Tutor> Tutor_person=new ArrayList<Tutor>();
public static void main(String[] args)
{
Hieracrhy obj=new Hieracrhy();
obj.start();
}
public void start()
{
getDetails();
System.out.println(Tutor_person);
}
//Function to read the songs from the file
void getDetails()
{
try
{
File file=new File("SongsList.txt");//Represents a file
FileReader fileReader=new FileReader(file);//FileReader connects to a text file
BufferedReader reader=new BufferedReader(fileReader);//For Efficient reading of file
// We use String variable to hold each line when the line is read one-by-one
String line=null;
//Read a line of the string and assign it to a string if it is not null just doo the func
while((line=reader.readLine())!= null)
{
addDetails(line);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
void addDetails(String lineToParse)
{
String[] tokens=lineToParse.split("/");
Tutor nextPerson=new Tutor(tokens[0]);
Tutor_person.add(nextPerson);
}
}
Now there is another class
import java.util.ArrayList;
public class Tutor
{
int Tutor_id;
String Tutor_name;
String Tutor_place;
int Tutor_age;
public void Set_Things_for_Tutor(int Tutor_id,String Tutor_name,String Tutor_place,int Tutor_age)
{
this.Tutor_id=Tutor_id;
this.Tutor_name=Tutor_name;
this.Tutor_place=Tutor_place;
this.Tutor_age=Tutor_age;
}
public int getuserid()
{
return Tutor_id;
}
public String getname()
{
return Tutor_name;
}
public String getdesignation()
{
return Tutor_place;
}
public int getage()
{
return Tutor_age;
}
}
Now there are inputs in a text file
11/devrath/hassan/22
but when i run the complete setup im getting the error
constructor tutor(string) is undefined
What is the reason for this error ..... can someone help me with a good i/p on this
Thanks
constructor tutor(string) is undefined
The error says it all.There is no constructor in your Tutor class which accepts string as an argument.
public Tutor {
//instance vars
public Tutor(String s){
//assign s to appropriate member variable
}
}
Btw, the design of the Tutor class seems bad. you initialize you instance members in your constructor(which ther are meant to do). you are currently initializing Tutor state in a method. i'd advice you to initialize them in the constructor.
Since you have not defined any constructor with "String" parameternthe JVM is unable to find it.
Define the constructor as follows:
public Tutor(String name)
{
//Do required initialization here
}
Well I think you have to rename Set_Things_for_Tutor to Tutor in your Tutor class. And remove the void string.
Your Tutor class does not have a constructor that accepts String as its parameter. if you want to pass a String in your Tutor class then add this to your code
public class Tutor{
//Other member variables
public Tutor(String yourString){
//Do some initializations
}
}
when you create an instance of a class , the constructor is called
MyClass obj = new MyClass();
this calls the default constructor
public MyClass(){}
but since you haven't made any parameterized consstructor
then JVM itself creates it for you
but if you want to pass some parameter to the constructor
MyClass obj = new MyClass(someInteger,someString);
in this case , JVM doent create any default constructor as you already have created a parameterized constructor
public MyCLass(int someInteger,String someString){}
in your case , you have not made any constructor ,
thus JVM only creates the default constructor
public MyClass(){}
so all you have is a non parameterized constructor
but what you are trying to access is a parameterized constructor
so all you have to do is to create a parameterized constructor in the class whose object are you creating ...
in your case
public Tutor(String string) {
System.out.println("add the code to initialize the class parameters here");
}
you calling code has one argument constructor and called code (Tutor) class doesn't have one argument constructor.
add constructor
public Tutor (String str)
{
//do your initialization here about 'str' variable.
}
Related
I am unable to grasp the concept of Method references in case of instance methods in Java
For example in the example below, the compiler is giving error in the list line.
I have seen the examples of String::toUpperCase.
I am confused over the point that
(1) String is a class and toUpperCase is instance method. Java allows String::toUpperCase
(2) Why it is not allowing in my case:- AppTest::makeUppercase
package mja;
import java.util.function.Function;
public class AppTest {
public String makeUppercase(String source){
return source.toUpperCase();
}
public void printFormattedString(String string, Function<String, String> formatter){
System.out.println(formatter.apply(string));
}
public static void main(String[] args) {
AppTest appTest = new AppTest();
String source = "Hello World!";
// Below statement compiled successfully
appTest.printFormattedString(source, appTest::makeUppercase);
// Getting error that non-static method can't be referenced from static context
appTest.printFormattedString(source, AppTest::makeUppercase);
}
}
Why it is not allowing AppTest::makeUppercase?
The short answer is that AppTest::makeUppercase isn't valid "reference to an instance method of an arbitrary object of a particular type".
AppTest::makeUppercase must implement interface Function<AppTest, String> to be valid reference.
Details:
There are 4 kinds of method references in Java:
ContainingClass::staticMethodName - reference to a static method
containingObject::instanceMethodName - reference to an instance method of a particular object
ContainingType::methodName - reference to an instance method of an arbitrary object of a particular type
ClassName::new - reference to a constructor
Every single kind of method reference requires corresponding Function interface implementation.
You use as a parameter the reference to an instance method of an arbitrary object of a particular type.
This kind of method reference has no explicit parameter variable in a method reference and requires implementation of the interface Function<ContainingType, String>. In other words, the type of the left operand has to be AppTest to make AppTest::makeUppercase compilable. String::toUpperCase works properly because the type of parameter and type of the instance are the same - String.
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
class ReferenceSource {
private String value;
public ReferenceSource() {
}
public ReferenceSource(String value) {
this.value = value;
}
public String doInstanceMethodOfParticularObject(final String value) {
return ReferenceSource.toUpperCase(value);
}
public static String doStaticMethod(final String value) {
return ReferenceSource.toUpperCase(value);
}
public String doInstanceMethodOfArbitraryObjectOfParticularType() {
return ReferenceSource.toUpperCase(this.value);
}
private static String toUpperCase(final String value) {
return Optional.ofNullable(value).map(String::toUpperCase).orElse("");
}
}
public class Main {
public static void main(String... args) {
// #1 Ref. to a constructor
final Supplier<ReferenceSource> refConstructor = ReferenceSource::new;
final Function<String, ReferenceSource> refParameterizedConstructor = value -> new ReferenceSource(value);
final ReferenceSource methodReferenceInstance = refConstructor.get();
// #2 Ref. to an instance method of a particular object
final UnaryOperator<String> refInstanceMethodOfParticularObject = methodReferenceInstance::doInstanceMethodOfParticularObject;
// #3 Ref. to a static method
final UnaryOperator<String> refStaticMethod = ReferenceSource::doStaticMethod;
// #4 Ref. to an instance method of an arbitrary object of a particular type
final Function<ReferenceSource, String> refInstanceMethodOfArbitraryObjectOfParticularType = ReferenceSource::doInstanceMethodOfArbitraryObjectOfParticularType;
Arrays.stream(new String[] { "a", "b", "c" }).map(refInstanceMethodOfParticularObject).forEach(out::print);
Arrays.stream(new String[] { "d", "e", "f" }).map(refStaticMethod).forEach(out::print);
Arrays.stream(new String[] { "g", "h", "i" }).map(refParameterizedConstructor).map(refInstanceMethodOfArbitraryObjectOfParticularType)
.forEach(out::print);
}
}
Additionally, you could take a look at this and that thread.
String::toUpperCase
is short version of
text -> {
return text.toUpperCase();
}
is again short version of
new Functon<String, String> (String text) {
Override
public String apply(String text) {
return text.toUpperCase();
}
}
so when you want AppTest::myMethod
you need
public class AppTest {
public String myMethod(){
return this.toString();
}
public void printFormattedString2(AppTest appTest, Function<AppTest, String> formatter){
System.out.println(formatter.apply(appTest));
}
public static void main(String[] args) {
AppTest appTest = new AppTest();
appTest.printFormattedString2(appTest, AppTest::myMethod);
}
}
because whole version looks so
appTest.printFormattedString2(appTest, new Function<AppTest, String>() {
#Override
public String apply(AppTest text) {
return text.makeUppercase2();
}
});
For simplicity, let us edit your class as below.
public class AppTest {
private String name;
public AppTest(String name){ this.name = name; }
public String makeUppercase() { //I have removed the argument here!!
return this.name.toUpperCase();
}
psvm main(){
AppTest appTest = new AppTest("Hello");
Stream.of(appTest).map(AppTest::makeUppercase).forEach(System.out::println);
//Here makeUppercase works of objects of type AppData similar to how String::toUpperCase works on object of type String!
}
}
This is accepted. Why?
Here, AppTest::makeUppercase is an instance method that operates on this instance of AppTest.
Why was yours not working?
appTest.printFormattedString(source, AppTest::makeUppercase);
This was not working because you are required to pass an implementation of Function. And, makeUpperCase() Function was not accessible from a non-static context since the method makeUpperCase() works on objects of type AppData. So, you need AppData instance to call this method!
Maybe you should change your method to be static and use it like this,
appTest.printFormattedString("Hello", AppTest::makeUppercase);
Why is the following code working?
appTest.printFormattedString(source, appTest::makeUppercase);
Because, you created an instance of AppTest and accessing the makeUppercase method (which is the implementation) and passing it as an argument to printFormattedString.
You need objects of a particular type to access the non-static method. But, You do not need objects of a particular type to access the static method.
String::toUpperCase works on instances of String. But you cannot access this method without having a String object to work on. Refer my comment in the code block to understand this better.
For my assignment, the our programs are tested by running them through the command line, as they take arguments in the forms of file names, so I have to make sure my program runs when run through the command line. When I compile it without issue through jGrasp and eclipse, but when I attempt to compile it through the command line, this is what I get:
Cleary.java.35: error: cannot access T Collections.sort(studentObjects, idSorter);
class file for T not found
I don't know what T is, and I've never used T as a class in my programs?
Relevant code:
Main Class:
package ClearyAssignment5;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Cleary {
public static void main(String[] args) {
//import the input file and add each line to an ArrayList of the students
try{
File input = new File(args[0]);
Scanner source = new Scanner(input);
ArrayList<String> listOfStudents=new ArrayList<String>();
while(source.hasNextLine()){
listOfStudents.add(source.nextLine());
}
ArrayList<Student> studentObjects = new ArrayList<Student>();
StudentIDComparator idSorter = new StudentIDComparator();
Collections.sort(studentObjects, idSorter);
FileWriter writer = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(writer);
for(int i=0;i<listOfStudents.size();i++){
(studentObjects.get(i)).printStudent(printWriter);
}
printWriter.close();
} catch(Exception e) {
System.out.println("Usage: ClearyAssignment4.Cleary input_file output_file");
}
}
}
Student Class:
package ClearyAssignment5;
import java.io.*;
import java.util.ArrayList;
import java.lang.*;
import jva.util.*;
public class Student {
//Initialize varaibles
String name;
int ID;
float GPA;
public Student(String studentName, int studentID, float studentGPA){
//Take the parameters which are passed in, and set them to the variables.
name = studentName;
ID = studentID;
GPA = studentGPA;
}
public int getID() {
return ID;
}
}
Comparator Class:
package ClearyAssignment5;
import java.util.*;
import java.lang.*;
import java.io.*;
class StudentIDComparator implements Comparator<Student> {
public int compare(Student a, Student b) {
return a.ID - b.ID;
}
}
I've removed some of the code which doesn't seem necessary for brevity... any help would be appreciated!
TL;DR: T is a generic type param that javac choked on somehow
T is a conventional name given to a Generic Type Parameter, which is used for Java's Generics system*. I'm not sure why the compiler choked on it, but the generics system in general has some occasional weird hiccups.
*An explanation of Generics (in case you haven't heard of them)
Imagine you are writing a class to hold a list of students. You want to be able to query if a person is on that list, as well as add people to that list. For now, this class will represent a course roster, so that professors can ensure that nobody is sneaking into their classes. Here is what the class will look like:
public class StudentList {
public boolean isOnList(Student s) { ... }
public void addToList(Student s) { ... }
}
Then imagine you need to create a new version of this class for the staff party at the end of the year, because only some staff are eligible (those who passed their performance review).
public class StaffList {
public boolean isOnList(Staff s) { ... }
public void addToList(Staff s) { ... }
}
Next, somebody asks you to create a new version of this class to keep track of the TAs for a course, since you can only pass assignments to grade to eligible TAs. You'd create yet another class:
public class TAList {
public boolean isOnList(TA t) { ... }
public void addToList(TA t) { ... }
}
You eventually get tired of writing such similar classes, so you want to create a single class which can perform all these functions. You would do so using Generics, so that client code can make a PersonList<Student> to hold Students, a PersonList<Staff> to hold Staff, a PersonList<TA> to hold TAs, and any other type of class you want.
public class PersonList<T> {
public boolean isOnList(T t) { ... }
public void addToList(T t) { ... }
}
The T is a generic type parameter here. When creating an instance of the class PersonList, you pass it a type inside the angle brackets. Then that type replaces all instances of T. The convention is to use single letter names, such as T for type, E for element, K for key, V for value, etc.
Well, I rewrote this program in a completely new directory, and it compiled and ran without issues. I don't know why that fixed it, but I guess it did.
This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Within my main method I'm trying to understand how to call up a variable from a different class.
I've attempted to break it down to the most simple solution possible just so I can get my head around the logic involved.
I have two classes within my package "var":
Class 1 - Source.java
package var;
public class Source {
int source1;
class setSource{
int source1 = 5;
}
}
Class 2 - Var.java
package var;
public class Var {
public static void main(String[] args) {
int Var;
Var = Source.setSource();
}
}
First time post here but I've spent 4 days and almost all my spare time trying to figure this out, please be gentle I'm dedicated but extremely newbie right now. Thanks in advance, I hope I've submitted this correctly.
Okay, I can sort of see what you were thinking but you've got some of the semantics incorrect. What you want to define is a method. A method takes the following structure:
<access modifier> <return type> <method name> (<method arguments>)
So for example
public void doSomething(String value) {
// This is the public method that returns nothing. It is called doSomething
// It expects a string value that it will call "value"
}
In your case, you want to create one of these, and you want to make a setter and a getter (or accessor and mutator if you're being posh).
Your Setter
This is just a normal method. Its purpose is to set the value of some class field. So let's define our class..
public class MyClass {
private int num;
}
Now we've got a class MyClass with a field num. But oh no, it's private, so let's create a setter so that the user can update the value.. Following our formula for methods, we start with a public access modifier. We then define the return type, which is void because it returns nothing. The name of the method should follow the java naming convention, which is the word "set" followed by the name of the member and finally the value for the setter.. Or all together:
public void setNum(int num) {
this.num = num;
}
This will update the value in the class with the value that you pass in. Excellent!
Your Getter
Well, this is nice and simple. Following our formula, it is a method that is public because everyone can access it; it returns something (in this case int) so that is the return type; the name follows the convention of "get" followed by the name and it expects no parameters.
public int getNum() {
return num;
}
This will return the value of num.
Finally, Using them!
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
// Create a new MyClass instance.
myClass.setNum(4);
// Update the value in the class with the number 4.
System.out.println("The number is " + myClass.getNum());
// Outputs: "The number is 4"
}
}
you are using static calls, so you have to set this variables public static :
public static int source1;
and access them directly:
Var = Source.source1;
Your concepts are not well polished.
Your classes should have been like this
public class Source {
private int source;
public void setSource(int src){ // Called setter
source = src;
}
public int getSource(){ // Called getter
return source;
}
}
And
public class Var {
public static void main(String[] args) {
int Var;
Source source = new Source();
source.setSource(10);
Var = source.getSource(); // Var has value 10 in it.
}
}
Source is a class, you'll need to create an object that's a member of this class and then call the method on it. Additionally, the syntax for your method call is incorrect.
package var;
public class Source {
int source1 = 1;
public void setSource(){
source1 = 5;
}
}
Then:
package var;
public class Var {
public static void main(String[] args) {
Source source = new Source();
System.out.println(source.source1);
source.setSource();
System.out.println(source.source1);
}
}
I hope that makes sense to you when you compile it and run.
(Note that Java is case sensitive. On the above example, Source is the class and source is the object).
An alternative would be to declare methods and fields as static (static methods are called directly on the class), but I would suggest you make sure you understand the basic concepts of class and object instantiation before moving on to that.
I've got this int variable inside the class StringSplit whose value I need to pass to another class called EndStatement to print out; can't really pass it as a parameter though I think. How can I best get the variable to where I need it? Can someone help with a hint? I've read the Java tutorials but don't quite get them. Variables and passing them around seem to be one of my Achilles' heels in Java programming.
EDIT TO ADD: parseCommands can call several different Statement classes e.g. EndStatement or PrintlnStatement depending on the first element of an Array parsed from a String which serves as a keyword to a HashMap called commandHash. The Statement classes implement the Directive interface which only has a method called execute with the parameterString[] parts. (EndStatement implements Directive). Expanded the parseCommands method to show what's going on.
public class StringSplit
{
public void parseCommands(String fileName)
{
//FileReader and BufferedReader to read a file with the code
//to execute line by line into an ArrayList myString
int lineCounter=0; //need to get this variable's value into class EndStatement
for (String listString: myString)
{
lineCounter++;
String[] parts=listString.trim.split("[\\s]+", 2)//split String into 2 parts
//to get commands
Directive directive= commandHash.get(parts[0])//parts[0] is the hashmap keyword
}
public class EndStatement implements Directive
{
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(lineCounter +"lines processed.");
}
public static void main (String[]args)
StringSplit ss = new StringSplit();
ss.parseCommands(args[0]);
}
This is my first time answering a question but I think I'm right.
In StringSplit you want to declare linceCounter in a data field.
public class StringSplit
{
public void parseCommands(String fileName)
{
lineCounter=0; //this is the variable I need to pass into a different class
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter()
{
return lineCounter;
}
private int lineCounter; //this is what I call a data field, you should declare these as private as oppose to public to comply with encapsulation
}
Then in your main method call getLinceCounter, then pass what it returns to EndStatment.
Does this make sense? Did I understand your question right?
public class StringSplit
{
private int lineCounter=0;
public void parseCommands(String fileName)
{
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter() {
return lineCounter;
}
}
public class EndStatement implements Directive
{
StringSplit ss = new StringSplit();
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(ss.getLineCounter() +"lines processed.");
}
public static void main (String[]args)
{
ss.parseCommands(args[0]);
}
}
I think you mix some terms. There is no such thing as passing variables from one class to another. I assume that what you want to do is simply be able to access (set/get) your variable outside StringSplit class. In order to do that you must declare lineCounter outside parseCommands method as StringSplit's property. Currently lineCounter is local to parseCommands method and as such cannot be visible/accessed outside that method not mentioning to be able to access it from outside a class/object. Do that:
public class StringSplit
{
public int lineCounter = 0;
...
Now you'll be able to access lineCounter from different methods of the same class and from methods outside your class. Making lineCounter public gives others full access to it. As 'Jon' has pointed out it may be dangerous sometimes but for this example case is acceptable. You may see how writing from outside can be prevented using 'Nurlan's' private field with member used to provide read acces only.