How can I run my program with many different arguments in Eclipse - java

I have a Java Application project in Eclipse and the executable receives parameters. The application then outputs a result value in a file. I want to, after running with many different parameters, compare these results.
If I could do something like this, like in a command prompt, it would be perfect:
run MyProgram --a hi --b 200
run MyProgram --a hello --b 333
...
run MyProgram --a something --b 10000
How can I do this with the Eclipse IDE?
If I can't do it by the IDE means, what would be the best way to manually do it (like with a .bat file)?

Basically, it's simple.
Click on Run -> Run Configurations
Click on the Arguments tab.
You want to type in all your input values into the Program arguments window, with spaces (blank characters) between each value.
Then just click Apply, followed by Run.

Go to run configuration, Arguments tab -> in the program arguments text box -> type space separated values to send arguments.
If you want to dynamically pass values on every launch and don't wanna open run configuration, then click on variables button and choose string_prompt. And provide variable name as follows -
${string_prompt: varName1}
${string_prompt: varName2}.
So you will be popped up a dialog asking you to enter the input values.
Better approach
would be to put all your input values in a txt file, read the input file line by line and run your logic and compare the results. This would make your life easier.
Hope this helps.

Better to use script to run your program several times with different parameters. Follow the below procedure to achieve this.
I have a java program which takes one input parameter. Below is the code
package org.stackoverflow;
public class Testing {
public static void main(String[] args) {
String inputString = args[0];
System.out.println("inputString:" + inputString);
}
}
I prepared one .bat file (TestingJavaProgramming.bat) to run this program again and again with different parameter and write the result into a .txt file after printing the result into console.
TestingJavaProgramming.bat file content
cd D:\All_POCs\WorkSpace\TestCoreJava\src
javac org\stackoverflow\Testing.java
java org.stackoverflow.Testing "This is 1st time testing">>result.txt
java org.stackoverflow.Testing "This is 2nd time testing">>result.txt
type result.txt
And the output after executing the batch file
D:\>TestingJavaProgramming.bat
D:\>cd D:\All_POCs\WorkSpace\TestCoreJava\src
D:\All_POCs\WorkSpace\TestCoreJava\src>javac org\stackoverflow\Testing.java
D:\All_POCs\WorkSpace\TestCoreJava\src>java org.stackoverflow.Testing "This is 1st time testing" 1>>result.txt
D:\All_POCs\WorkSpace\TestCoreJava\src>java org.stackoverflow.Testing "This is 2nd time testing" 1>>result.txt
D:\All_POCs\WorkSpace\TestCoreJava\src>type result.txt
inputString:This is 1st time testing
inputString:This is 2nd time testing
You can also see the output inside the result.txt file.Hope my hints will help you.

Related

Java location path regex split

I've "inherited" existing Java Selenium & Cucumber framework which was written mostly for OS usage. I'm using Windows and I'm trying to fix & run it on Windows.
My first problem is specifing corrent file path, this is how it was written for OS:
private String getProjectName(Scenario scenario) {
return Arrays.asList(scenario.getUri().getPath().replace(System.getProperty("user.dir"), "").split("/")).get(5);
}
Error which I'm receiving is:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 1
As for Windows we're using backlashes I've tried switching "/" into "" but as error appears (+ after my investigations) I've tried with "\\\\" but actually error remains the same as above.
I'm aware that providing only portion of my code and it may be hard but for the first glance can you tell me:
If that method may work on Windows or this should be completely refactored?
Is System.getProperty("user.dir") correct solution?
How to correctly pass backslashes?
Why they're taking .get(5)?
I can guess:
This method is taking the project name that is likely the name of a certain folder in the folder structure where scenario file located.
This is why they took 5th element. Because on the 5th level there was the folder which represented the project.
The used approach look very arguable. At least because there are some redundent steps like converting to list.
Now. How would you go:
The proper way is to use java.nio.file.Path (starts from Java 7) that takes care of differnt OS-specific things.
So your code might look like:
private String getProjectName(Scenario scenario) {
return Path.of(scenario.getUri()).getName(5)
}
P.S. - of course you have to change 5 to catch a proper position of the required folder in your structure.

How do I pass an arg to convert between numbers and strings

I am reading through the java tutorials, and I don't understand when it says
"The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:"
What I mean is how do I pass the values to the program. A piece of the code is this.
float a = (Float.valueOf(args[0])).floatValue();
float b = (Float.valueOf(args[1])).floatValue();
I have tried changing "args[0]" to "4.5" and "args[1]" to "87.2" which are the given values from this page.
https://docs.oracle.com/javase/tutorial/java/data/converting.html
Upon doing so I receive "requires two command-line arguments." which is the else part of the code. I'm pretty sure I am being oblivious to this. I have tried looking for anything regarding passing arguments but i can't find exactly what to do.
I have also tried creating two "string" values named one and two with the same values as above and inputting the string name into the args positions but still received the same outcome.
Is it something simple such as requesting an input from the user or should I manually put the values in there and if I need to add the values into the argument then how would I go about doing so.
The arguments passed to the main methods are the one typed when starting your java application from command line. An revelant example for your case would be :
java YourProgram 4.5 87.2
Then you will be able to access them from args[0] and args[1] as explained in the tutorial.
For more examples read the Command-Line arguments part of the java tutorial.
If you're running the program from a command line (typing something like java ValueOfDemo into a terminal), you would type java ValueOfDemo 4.5 87.2 to pass 4.5 and 87.2 as the first and second arguments, respectively. If you're running the program using an IDE such as Eclipse or NetBeans, search for that program's documentation on how to pass command line arguments to the program.
In general, command line arguments are arguments that are passed to the program you're running when the program is started. You can also ask the user for input while your program is running, but you would explicitly write code to do so and accept the value.
See this page for more information: https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
Open cmd(window key + r) and compile by command: javac yourClass.java and then execute by command: java yourClass 4.5 87.2 you will see result

Changes a word in a file that you don't know using java

Backstory:
I am creating a LTspice program, where I am creating a circuit with over 1000 resistors.
There are 9 different types resistors. I need to change the value of each type of resistor, many times. I can do this manually but I don’t want to. The file is like a text file and can be read by a program like notepad. The filetype is .asc
I was going to create a java program to help me with this.
File Snippet:
SYMATTR InstName RiMC3
SYMATTR Value 0.01
SYMBOL res -1952 480 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName RiMA3
SYMATTR Value 0.01
SYMBOL res -2336 160 R0
SYMATTR InstName ReC3
SYMATTR Value 8
Question:
How can I changes a word, I don´t know, in a file, but I know where it is, compared to another word I know?
An example:
I know the word "RiMC3", I need to changes the 3th word after this word to "0.02".
In the file Snippet the value is "0.01", but this will not always be the case.
My Solution:
I need a place to start.
Is this call something special? I have not found anything like this on google.
If you want to do this programmatically, you need to think about the limitations and requirements.
We don't know exactly how you want to do this, or in what context. But you can write this out on paper, in English, to give you a place to start.
For example, if we are going to make a standalone Java program (or class) to do this, and given simple line-oriented text, a naive approach might be:
Open the file for read
Open a file for write
Scan the file line by line
For each line:
Match the pattern or regular expression you are looking for and, if
it matches, modify the line in memory
Write out the possibly modified line to the output file
Finish up:
Close the files
Rename the output file to the input file
Buffering, error handling, application domain specifics are left as an exercise for the reader.

Input In Java- How does it work?

Hey guys, with a lot of help from you i was managed to write this nice code (I'm new in it, so kind of exciting.. :) )
And still I have not understand how can I input this code.
first of all, I get an this error in the console line (I'm using Eclipse):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at NumberConverter.main(NumberConverter.java:5).
What does that mean?
I just want to chack whether it works, and I can't call the function/program any how.
I used to call in an "old fashion way", like in scheme, to the function that I wrote and see if something happens. How does it work in java? Do we call the program itself? function? what and where do we write? -I want to chack if it works, doesn't matter how, and I'll be glad to know how can I plugin input.
Thank you so much!
public class NumberConverter{
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
toOctal(i);
toHex(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
public static void toOctal(int int1){
System.out.println(int1 + " in octal is");
System.out.println(Integer.toOctalString(int1));
}
public static void toHex(int int1){
System.out.println(int1 + " in hex is");
System.out.println(Integer.toHexString(int1));
}
}
It means there was an ArrayIndexOutOfBoundsException at line 5 of NumberConverter. This is most likely going to be this line (if the full source contains a package statement followed by a blank line, this will be line 5):
int i = Integer.parseInt(args[0]);
Which tries to access the first argument you passes to the program, since you did not pass any arguments to the program the arbs array is empty and attempts to access args[0] results in ArrayIndexOutOfBoundsException.
If you were running this from the command line you it should look something like this:
$ java com.mypackage.NumberConverter 1
Here $ is the prompt, com.mypackage is presumed to be the package name and 1 is the command line argument which you will be able to access via args[0]`.
Since you are using eclipse and not via a command line here is a nice blog post on adding command line arguments from within eclipse.
you have to set arguments for app start up. You can do this in Run Configuration editor (Right click on project -> Run as.. -> Run Configurations). In Arguments tab you can put one to program Arguments field. One argument per line (eg. 5).
The ArrayIndexOutOfBoundsException occurs because of empty args array that you want to take first element of empty array - args[0]. You can't do this because the array is empty if no app start up arguments are set.
ArrayIndexOutOfBoundsExceptions means (from JavaDoc):
Thrown to indicate that an array has
been accessed with an illegal index.
The index is either negative or
greater than or equal to the size of
the array.
From your exception, args[0] throws ArrayIndexOutOfBoundsExceptions because 0 is greater than or equal to args.length. My suggestion is to find out what arguments is the OS returning to your JVM which is then passed to your app and see if args[0] is initialized and populated.
Also, running a program from Eclipse requires you to set arguments through Run Configurations.
an ArrayIndexOutOfBoundsException is thrown when you try to access an index outside of an array. Let's say that I have an array of size 2. I can access the first and second elements using the indices 0 and 1 respectively, but if I try to access the element in index 4, an exception is thrown:
public static void stam() {
int[] array = { 0, 1 };
// this will print 0
System.out.println(array[0]);
// this will print 1
System.out.println(array[1]);
// this will crash the program
System.out.println(array[4]);
}
Your instinct was correct that you can easily test your program using input, although using a literal value and a variable are probably an easier, and certainly more flexible option. In any case, you can set up the run configuration to include command line arguments via the Run > Run Configurations... window.
As you probably guessed, the reason why your program was crashing is because you try to access the first command line argument in line 5 of your class, but the argument wasn't there, so the array has 0 elements.
A slightly more flexible way of running a java program with command line arguments is by calling the main method of a different class, and manually passing it a String array. But if you want to test your methods quickly, just pass them literal values.

difference between System.out.println() and System.err.println()

What is the difference between System.out.println() and System.err.println() in Java?
In Java System.out.println() will print to the standard out of the system you are using. On the other hand, System.err.println() will print to the standard error.
If you are using a simple Java console application, both outputs will be the same (the command line or console) but you can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.
Also, IDEs like Eclipse show System.err in red text and System.out in black text by default.
System.out is "standard output" (stdout) and System.err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model. Most modern programming environments (C, Perl, etc.) support this model.
The standard output stream is used to print output from "normal operations" of the program, while the error stream is for "error messages". These need to be separate -- though in most cases they appear on the same console.
Suppose you have a simple program where you enter a phone number and it prints out the person who has that number. If you enter an invalid number, the program should inform you of that error, but it shouldn't do that as the answer: If you enter "999-ABC-4567" and the program prints an error message "Not a valid number", that doesn't mean there is a person named "Not a valid number" whose number is 999-ABC-4567. So it prints out nothing to the standard output, and the message "Not a valid number" is printed to the error output.
You can set up the execution environment to distinguish between the two streams, for example, make the standard output print to the screen and error output print to a file.
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err to errors.txt file.
System.out's main purpose is giving standard output.
System.err's main purpose is giving standard error.
Look at these
http://www.devx.com/tips/Tip/14698
http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F
System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.
Most of the IDEs show this in red color (System.err.print).
this answer most probably help you it is so much easy
System.err and System.out both are the same both are defined in System class as reference variable of PrintStream class as
public final static PrintStream out = null;
and
public final static PrintStream err = null;
means both are ref. variable of PrintStream class.
normally System.err is used for printing an error messages, which increase the redability for the programmer.
A minor difference comes in both when we are working with Redirection operator.
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}

Categories

Resources