Call the program with exactly one argument result - java

Keep getting error of "Call the program with exactly one argument!", but am unsure where I need to make changes to run the program correctly. Thanks!!
class Main {
private static ArrayList<ArrayList<int[]>> list;
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("Call the program with exactly one argument!");
System.out.println("argument 1: path to map file");
System.out.println("argument 2: path to airports file");
System.out.println("argument 3: path to flights file");
System.exit(-1);
}

You have to call your main method with three parameters as you point in your code (args.length). In order to call your method via command line:
- java Main.java param1 param2 param3
If you want to call main method using only one parameter, then you'll get println messages you write.

Related

Passing values to java program from a command line, how does it work?

So I always use Eclipse to run my java stuff, I have no clue how to use command prompts. I have an assessment that will be graded by a bot where 2 string parameters will get passed into a function which returns a boolean value.
The bot is going to use a command like "java main.java xyz zyx" to open the file
(assuming xyz and zyx are the strings).
So my question is, to catch those 2 strings, do I have to use 2 variables to catch the 2 string. For example:
string1 = Scanner.nextln(); // This will catch "xyz" into string1??
string2 = Scanner.nextln(); // This will catch "zyx"??
Or does string 1 catch both "xyz zyx" and I have to use a loop to separate them into 2 strings? Thanks in advance :)
Your Main method can be used to catch arguments passed from command line.
public static void main(String[] args) {
System.out.println(args);
}
public static void main(String[] args) {
...
}
Is your program written like this? As in the signature of the main function. The signature holds them as strings in an array. Then you have to process those strings.

JUnit Passing No arguments to main Method Java

I'm trying to test my main method (which should accept exactly one argument) for no arguments passed. Can't seem to understand what am I missing here to achieve that.The nature of my program is such that it reads input from a file, creates objects by passing parameters read from the file, and displays output.
Failure Message:
org.junit.ComparisonFailure: Expected :Please pass one argument
Actual :
Here's my Unit Test:
#Test
public void givenNoParameter_shouldAskForOne() throws IOException {
String[] args = {};
String output;
try (ByteArrayOutputStream bOutput = new ByteArrayOutputStream()) {
System.setOut(new PrintStream(bOutput));
Main.main(args);
bOutput.flush();
output = bOutput.toString();
}
String newLine = System.getProperty("line.separator");
String[] breakDownOutput = output.split(newLine);
assertEquals(1, breakDownOutput.length);
assertEquals("Please pass one argument", breakDownOutput[0]);
}
Main Method:
public static void main(String[] args) {
if(args.length == 1) {
DisplayOrder.setFilePath(args[0]);
DisplayOrder.display();
} else{
System.err.println("Please pass one argument");
}
}
I've realized I was using System.err.println() in my main. Changing that to System.out.println() fixed it.
Not showing your main method, my only guess is, that you do not write anything to "System.out" in your main, especially there is no System.out.println("Please pass one argument"); statement which is executed.
So, your unit test fails perfectly for a not expected value in "breakDownOutput[0]".
What you have to do is to make certain that the System.out.println("Please pass one argument"); is executed if no arguments were provided to your main.
Also check your class name Main.main(...) since there might be other Main classes imported which will never print out your expected values to System.out

Get methods using Java Reflection Class

Hi guys im new to all this test automation stuff and trying to learn following a tutorial but im stuck trying to run this code.
I get an exception
Exception in thread "main" java.lang.NullPointerException
at executionEngine.DriverScript.execute_Actions(DriverScript.java:45)
at executionEngine.DriverScript.main(DriverScript.java:39)
dunno whats wrong as im following a tutorial so i assume everything should be working.
package executionEngine;
import java.lang.reflect.Method;
import config.ActionKeywords;
import utility.ExcelUtils;
public class DriverScript {
//This is a class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static ActionKeywords actionKeywords;
public static String sActionKeyword;
//This is reflection class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static Method method[];
//Here we are instantiating a new object of class 'ActionKeywords'
public DriverScript() throws NoSuchMethodException, SecurityException{
actionKeywords = new ActionKeywords();
//This will load all the methods of the class 'ActionKeywords' in it.
//It will be like array of method, use the break point here and do the watch
method = actionKeywords.getClass().getMethods();
}
public static void main(String[] args) throws Exception {
//Declaring the path of the Excel file with the name of the Excel file
String sPath = "D://Tools QA Projects//trunk//Hybrid Keyword Driven//src//dataEngine//DataEngine.xlsx";
//Here we are passing the Excel path and SheetName to connect with the Excel file
//This method was created in the last chapter of 'Set up Data Engine'
ExcelUtils.setExcelFile(sPath, "Test Steps");
//Hard coded values are used for Excel row & columns for now
//In later chapters we will use these hard coded value much efficiently
//This is the loop for reading the values of the column 3 (Action Keyword) row by row
//It means this loop will execute all the steps mentioned for the test case in Test Steps sheet
for (int iRow = 1;iRow <= 9;iRow++){
//This to get the value of column Action Keyword from the excel
sActionKeyword = ExcelUtils.getCellData(iRow, 3);
//A new separate method is created with the name 'execute_Actions'
//You will find this method below of the this test
//So this statement is doing nothing but calling that piece of code to execute
execute_Actions();
}
}
//This method contains the code to perform some action
//As it is completely different set of logic, which revolves around the action only,
//It makes sense to keep it separate from the main driver script
//This is to execute test step (Action)
private static void execute_Actions() throws Exception {
//This is a loop which will run for the number of actions in the Action Keyword class
//method variable contain all the method and method.length returns the total number of methods
for(int i = 0;i < method.length;i++){
//This is now comparing the method name with the ActionKeyword value got from excel
if(method[i].getName().equals(sActionKeyword)){
//In case of match found, it will execute the matched method
method[i].invoke(actionKeywords);
//Once any method is executed, this break statement will take the flow outside of for loop
break;
}
}
}
}
The problem is that you do never fill something into your method[] array. In the constructor, the array would be filled, but it is never called. Therefore, try calling the constructor inside the main method.
public static void main(String[] args) throws Exception {
new DriverScript();
...
In this line you need to change "Test Steps" to 'Sheet1' (or change the Excel sheet name to "Test Steps"):
ExcelUtils.setExcelFile(sPath, "Test Steps");

Modifying a main method to take a text file when compiling the java file

How can I make a main method take a text file as an argument on the command line?
So for example
java ClassWithMainMethod textFileNeededInMainMethod.txt
I've been told this is possible but I'm not sure how it's done.
You use the String[] args from the Java program entry point like
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("no file provided");
System.exit(1);
}
File f = new File(args[0]);
// ...
}
That if could be used to set a default file if one isn't provided. Finally, it's a good idea to use File.canRead() before you try and read from a file.
The arguments passed to main are of type string so you'd pass the name of the file or path of the file and then create a file object and then read its content.
You can't pass the type file to a java main class
In your main method, the args array contains any arguments. For example, if you typed java ClassWithMainMethod textFileNeededInMainMethod.txt, then you could read the argument like this:
public static void main(String[] args) {
String file = "";
if(args.length > 0) file = args[0];
}

Java: Check if command line arguments are null

I am looking to do some error checking for my command line arguments
public static void main(String[] args)
{
if(args[0] == null)
{
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}
However, this returns an array out of bounds exception, which makes sense. I am just looking for the proper usage.
The arguments can never be null. They just won't exist.
In other words, what you need to do is check the length of your arguments.
public static void main(String[] args) {
// Check how many arguments were passed in
if (args.length == 0) {
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}
#jjnguy's answer is correct in most circumstances. You won't ever see a null String in the argument array (or a null array) if main is called by running the application is run from the command line in the normal way.
However, if some other part of the application calls a main method, it is conceivable that it might pass a null argument or null argument array.
However(2), this is clearly a highly unusual use-case, and it is an egregious violation of the implied contract for a main entry-point method. Therefore, I don't think you should bother checking for null argument values in main. In the unlikely event that they do occur, it is acceptable for the calling code to get a NullPointerException. After all, it is a bug in the caller to violate the contract.
To expand upon this point:
It is possible that the args variable itself will be null, but not via normal execution. Normal execution will use java.exe as the entry point from the command line. However, I have seen some programs that use compiled C++ code with JNI to use the jvm.dll, bypassing the java.exe entirely. In this case, it is possible to pass NULL to the main method, in which case args will be null.
I recommend always checking if ((args == null) || (args.length == 0)), or if ((args != null) && (args.length > 0)) depending on your need.
You should check for (args == null || args.length == 0). Although the null check isn't really needed, it is a good practice.
if i want to check if any speicfic position of command line arguement is passed or not then how to check?
like for example
in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?
public class check {
public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}
So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:
so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it.
need assistance asap.
If you don't pass any argument then even in that case args gets initialized but without any item/element.
Try the following one, you will get the same effect:
public static void main(String[] args) throws InterruptedException {
String [] dummy= new String [] {};
if(dummy[0] == null)
{
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}

Categories

Resources