className.main(new String[]{"filename.txt"})? - java

I created a class that does some file parsing for me. I made it possible to be started as a standalone application, taking file name from command line.
Now I created another class, that needs to take advantage of what the first class is doing, and I tried to call its main method like this:
className.main(new String[]{"filename.txt"});
However, it seems that things aren't doing so fine, because I was getting some null pointer exceptions. When I inserted system.out.println(args[0]) to see what was going on, I got the reference to the resource, and not the string I was expecting.
Here is more code:
// this is from the class that is reffered as 'new one'
// Cal the maze solver now for out.txt
String[] outFile = new String[]{"out.txt"};
MazeSolver.main(outFile);
// this is part of the MazeSolver main method
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Usage: java MazeSolver ");
System.exit(0);
}
// this is the part where i tried to debug
System.out.println(args.toString());
// and this is the error message that i got in terminal
// [Ljava.lang.String;#63b9240e <---------------------------------------
//ROWCOUNT: 199
//Exception in thread "main" java.lang.NullPointerException
Do I need to create one more method, doing the exact same thing, but with different name?
Thanks

I'm just answering the part about printing an array of Strings:
System.out.println(args.toString());
This won't work, Array.toString() just returns an internal representation. You will want to use the helper method Arrays.toString(arr) in the Arrays class:
System.out.println(Arrays.toString(args));
Or, if you are dealing with a multi-dimensional array, use Arrays.deepToString(arr):
final Object[][] arr = new Object[3][];
arr[0]=new String[]{"a","b","c"};
arr[1]=new Integer[]{1,2,3,4,5};
arr[2]=new Boolean[]{true,false};
System.out.println(Arrays.deepToString(arr));
Output:
[[a, b, c], [1, 2, 3, 4, 5], [true, false]]

You are not supposed to use main for that purpose. Refactor your old class and create a new method called parse(String path). This new method should do whatever main did to make everything work.
public static void parse(String path)
By making it public other classes can access it and static means you don't need to create an instance of the class to use it. Your other class that wants to use the first class would do
MyFirstClassName.parse("file.txt");

I don't get it. Since main is your entry point I don't understand how you suppose to call it from an outside method if it is the first thing that is called when program starts. This will work only if you have two main methods declared in two different classes and you call one from the another, taking care that this last one is the one invoked by JVM at application start.
In any case I suggest you to avoid using main as a name for a generic method, it is not a keyword but I suggest you to just rename it to something else.

Related

Setting class fields and then modifying them in in methods

I dont get to write java frequently and when i do its usually expanding others code so I apologize for the basic nature of this question. I have a class that is used to test another application. each method in this class is an individual test. there are hundreds of tests in this class. as this class evolved, each new method was cloned, so there wasn't a lot of foresight into the overall design. Im trying to refactor this class so to make it easier to maintain.
So for the question - Each method has a block of code that populates 2 string arrays. Array 1 is a list of things you want turned on. Array 2 is a list of things you want off. Those 2 arrays are passed into another method as parms. The problem is that if you create a new "thing you want on/off" you have to set it in each method. Id like to move array1 and array2 to properties. See the code example below
Public class MyClass{
String[] OnThings = {"Thing1", "Thing2"}
String[] OffThings = {"Thing3"}
}
protected void Test1{
/**Below method iterates both arrays and turns things on or off**/
turnThingsOnOrOff(OnThings, OffThings)
/**Do a bunch of testing here**/
}
protected void Test2{
/**This particular test I want to turn off Thing 1**/
OnThings.Remove{"Thing1"}
OffThings.Add{"Thing1"}
turnThingsOnOfOff(OnThings, OffThings)
/**Do a bunch of testing here**/
}
As the code currently exists, if you to add a new thing (Thing4) and test it in every test, you have to go into each of the 100's of methods and add it to the list of "OnThings"
With the proposed code, you just add Thing4 once to the class property and it will run in all the tests. If you want turn if off for a few tests, then you can go modify those methods using .Add and .Remove.
Currently , the array of strings do not seem to support Add or Remove
Make the onThings and offThings properties static so you will be able to use them outside the class without creating new object each time.
Also, if you want to add or remove data from the arrays, use ArrayList<String> instead of String[]. ArrayLists are dynamic in size and objects can be added or removed from them easily.
Here is the modified code :-
Public class MyClass{
public static ArrayList<String> OnThings = new ArrayList<String>(Arrays.asList("Thing1", "Thing2"));
public static ArrayList<String> OffThings = new ArrayList<String>(Arrays.asList("Thing3"));
}
protected void Test1{
/**Below method iterates both arrays and turns things on or off**/
turnThingsOnOrOff(MyClass.OnThings, MyClass.OffThings)
/**Do a bunch of testing here**/
}
protected void Test2{
/**This particular test I want to turn off Thing 1**/
OnThings.Remove{"Thing1"}
OffThings.Add{"Thing1"}
turnThingsOnOfOff(MyClass.OnThings, MyClass.OffThings)
/**Do a bunch of testing here**/
}
More about ArrayList can be found here.

Understanding constructors (very simple code)

public class HelloWorldV3
{
//default constructor
HelloWorldV3()
{
}
//print two lines of text
public void printTwoLines( )
{
System.out.println("Hello, Virtual World!");
System.out.println("It is a great day for programming.");
}
//main method
public static void main(String [] args)
{
HelloWorldV3 hello = new HelloWorldV3( );
hello.printTwoLines();
}
Hi, I am beginning to learn about constructors, and I am having trouble understanding some code. In the program above, I know that a constructor was created, but it is empty. The printTwoLines() function prints the two lines, and the main method uses the constructor to call the function. I had questions about why there needs to be the "HelloWorldV3 hello = new HelloWorldV3();" line, and what would happen if there was actually something in the constructor.
The:
HelloWorldV3 hello=new HelloWorldV3();
line makes a variable called hello. Hello is a different type of variable than what you are probably used to, and doesn't store a number, or integer, or anything like that, but an object (really the location of the object, but don't worry about that for now). You could also write it as :
HelloWorldV3 hello;
hello=new HelloWorldV3();
just as you would write:
int i;
i=5;
You can then access either the hello variable or the i variable.
As for the second part of your question, anything in the constructor would be called when the code:
new HelloWorldV3();
is executed. So you could put some code inside the constuctor like this:
public HelloWorldV3() {
System.out.println("In the constuctor");
}
It's just that you allocating the space with new operator for your HelloWorldV3 object.
It's always good to define state in constructor. By state i mean is, if you have say int field, you could initialize it to say default value that might be appropriate when you create your object (say to value 10)
The constructor will initilize your object "hello" of type "HelloWorldV3".
If there is a code in the constructor, it will be executed when calling "new HelloWorldV3( )" in your first line of code of the method. So it will be executed before the method "printTwoLines".
I hope I was clear :)
Thanks.
You need the line
HelloWorldV3 hello = new HelloWorldV3( );
because that is what creates an instance (object) of the class HelloWorldV3, allowing you to call its methods and access its fields (if any).
Java does some things behind the scenes to instantiate an object, and the concept of a constructor exists to allow you to specify code to execute (mostly initialization stuff) when Java is creating an instance of the class.
If there was code in the constructor, that code would execute when the line
HelloWorldV3 hello = new HelloWorldV3( );
executes.
To answer your question with a question, if there wasn't that line, then how would you ever call the printTwoLines() method?

Why array created with values have to static to access it in the main? and what are the advantages of referenced array?

`
class under
{
static int[] locations ={2,3,4};//arrays declared with values in class under
}
class understand
{
String c;
public static void main(String[] args)
{
under d=new under();
System.out.println(under.locations[0]);
understand[] u;//next array created created in the main class using //reference//
u = new understand[2];
u[0]=new understand();
u[0].c="ab";
System.out.println(u[0].c);
}
}`
I have the following questions in this code they are:
1.)The first array that I create is of integer type named locations with values inside it.Why do I have make it static in order access it in the main class?
2.)The second concern is the array created in the main class using reference will not be created if i don't name it same as a class. Every time I create using array with reference ,I have to have the same class of it. Why do I need to have a class of the same as the array ? What is the default type of the array created in the main? . The array with reference for example: understand[] array in the main ,if created out the main with references will not be accepted. Can I create a referenced array with out a class of it?
3.)Rather than creating the array using references ,I can directly give values to it then use it accordingly.Why do I need a reference to an array?
Thanks a lot for having attention. Your opinion on this is very valuable to me.It means a lot when my doubts get cleared by the erudite members of Stack overflow.
enter code here
main() method is static, you can only run static code in static context
I'm sorry bu most of your questions in point 2 don't make sense...
You need reference to every object in Java because objects without reference are collected by garbage collector (permanently removed from memory)
EDIT:
I tried reading point 2 again - still don't get it...
You cannot make a static reference to a non-static field.
Like ordinary objects, arrays are accessed through references.
Just like Lucas wrote: you can only run static code in static context
There is no such thing as default type of an array created in main. Referring to other questions: array definition in java looks like that:
T id = new T[initialsize];
T id = new T() { instanceofT_1, instanceofT_2};
So in your case you didn't name an array with the same name as class. What you did was a definition of array u of type understand[].
Again, as Lucas wrote: every object in Java can not exist without reference. Java compiler will not allow you to write something like below:
new String[] {};
It'll report an error "The left-hand side of an assignment must be a variable".

Difference in passing an object to an arraylist (initializing once and more than once)

This is my main class MainClass and it has an arraylist MyList. I created an object for ExtractClass [not shown] extract and added it to my MyList. There is also another class PressClass [not shown]
public class MainClass {
public static void main(String[] args) {
ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();
ExtractClass Extract = new ExtractClass();
MyList.add(Extract);
MyList.add(Extract);
PressClass Press = new PressClass();
Press.pressMethod(MyList);
}
}
Here is another version of the above program. I have initialized an object Extract and then added to MyList and i repeated it once more.
public class trailclass {
public static void main(String[] args) {
ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();
ExtractClass Extract;
Extract = new ExtractClass();
MyList.add(Extract);
Extract = new ExtractClass();
MyList.add(Extract);
PressClass Press = new PressClass();
Press.pressMethod(MyList);
}
}
I got the same output for both programs. What is the difference between both? Does any of the above two codes breaks the rules of java? As a developer, which piece of code does one prefer?
It depends on what you try to achieve...
In the first snippet you are adding the same ExtractClass instance twice to the list and in the second code snippet you are adding 2 different ExtractClass instances to the list. As I am not aware to the internals of your ExtractClass I can determine which of the codes is "right".
Simple answer is that you are creating two objects, one of which you don't need. The garbage collector wont destroy it however because it is in the ArrayList MyList so a reference to it is still reachable.
In the first example the same object is being added to an ArrayList twice. In the second example, an object is made and added to to the ArrayList. After that, a new object is created and it too is added tot he ArrayList. The objects may have the same values (However you made your constructor) but the references are different.
If you want more explanation please ask.
What is the difference between both?
Firt one creates one single object and add it twice to the list
In the second you create two different(1) objects and add each one once to the list, this is what actualy you will in most cases intend to do.
Does any of the above two codes breaks the rules of java?
Technically not. List allows the same object to appear more than one time in it. Semantically, it depends whether it is your intetion to have the same object more than one time in the list or not.
As a developer, which piece of code does one prefer?
In general you mean the have the second version.
(1) different depends on your implementation of hashCode and equals. The defaults from the base class Object just dows a reference check. So the different instances will not be equal and thus different. You can see the impact of this when you use the List#contains method. Depending on your implementation of the former methods and on which instance you pass to it you may get different results.
The presented 2 solutions are not the same. The first adds the same object twice to the list while the second adds 2 different instances to the list.
Btw initializing a local variable in the same line is more compact and you should prefer that if it is a simple object creation:
ExtractClass Extract = new ExtractClass();
Also note that if you don't use the local variable, you can simply leave that out and add directly to the list:
MyList.add(new ExtractClass());
Also by convention you should start your variable names with lowercased letters and start your types (e.g. class name) with uppercased letter.
As per your current Implementation Both programs would work because you are adding object new ExtractClass()
with default implemnentation in the list. First program adds same object twice while the second adds 2 different instances to the list.
If you have scenario where ExtarctClass constructor accepts some parameter lets say File destDir you will be left with second Option because you may have to provide different destDir for different objects
with said above your second program would look like below
public class trailclass {
public static void main(String[] args) {
ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();
ExtractClass Extract;
Extract = new ExtractClass(new File("c:\temp"));
MyList.add(Extract);
Extract = new ExtractClass(new File("c:\temp"));
MyList.add(Extract);
PressClass Press = new PressClass();
Press.pressMethod(MyList);
}
}
This can further be written as below
public class trailclass {
public static void main(String[] args) {
ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();
MyList.add(new ExtractClass(new File("c:\temp")));
MyList.add(new ExtractClass(new File("c:\temp")));
PressClass Press = new PressClass();
Press.pressMethod(MyList);
}
}

Java pass and construct class as function argument

I was using a library called Mallet. It is by far the most complicated Java Library I have ever used. They provide tutorials and code template and I was trying to understand it. However, I came across this line of code:
TransducerEvaluator evaluator = new MultiSegmentationEvaluator(
new InstanceList[]{trainingData, testingData},
new String[]{"train", "test"}, labels, labels) {
#Override
public boolean precondition(TransducerTrainer tt) {
// evaluate model every 5 training iterations
return tt.getIteration() % 5 == 0;
}
};
Please don't pay too much attention on the term "transducer". What is passed into this function? Two classes? What is this new String[]{}? I am just very very confused with this syntax as I have never seen it before.
This is the code for this method:
public MultiSegmentationEvaluator (InstanceList[] instanceLists, String[] instanceListDescriptions,
Object[] segmentStartTags, Object[] segmentContinueTags)
Can someone tell me what this weird construct is?
This construct does several things:
Creates a subclass of MultiSegmentationEvaluator without giving it a name
Provides an override of the precondition(TransducerTrainer tt) method
Instantiates the newly defined anonymous class by passing two string arrays and then labels to the constructor that takes four parameters.
Assigns the newly created instance to the evaluator variable.
The code uses the anonymous class feature of Java - a very handy tool for situations when you have to subclass or implement an interface, but the class that you define is used in only one spot in your program.
Consider this code:
String[] stringArr = new String[]{"train", "test"};
Does it make any sense now? It is a String array! =) Here's even more stupid code to prove my point:
new String[]{"train", "test"}.getClass() == String[].class
InstanceList[]
means that you need to have a list of objects that are of they type InstanceList, same goes for String[]
for these:
Object[]
means that anything that is a sublass of Object (any object) can be passed as arguments for the last two paramaters.
In the top code this is exactly what they're doing but they create new objects for InstanceList and String,and then labels is the 2 objects they're passing.

Categories

Resources