Input In Java- How does it work? - java

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.

Related

Array of integers as command line argument along with other commands

So for my JAVA program the user has to give 6 arguments using the command line or Linux environment. One of these 6 commands is a list of numbers which I have them in the program as array of integers.
I'm not quite familiar with how it would be able to read in the list of numbers as the 6th argument ? Wouldn't the computer think of it as several arguments and not multiple numbers for one argument ?
Any help would be appreciated:)
That's correct, Java will interpret multiple spaced arguments as each their own, and put each separately into the String[] args arguments for your main. However, you can still handle this by specifying that the last argument must be a list of numbers. Doing this, you can simply loop after the 5th argument, and be confident that everything you're getting should be a part of the list.
public static void main(String[] args) {
// handle first 5 args
for (int i = 5; i < args.length; ++i) {
// everything accessed by args[i] at this point is a part of your list
}
}
You can then specify input via the java command
java -jar MyApp.jar arg1 arg2 arg3 arg4 arg5 int1 int2 int3 int4 int5 int6
# int1 to int6 will be read by the loop

How can I overcome ArrayIndexOutOfBoundException for Integer.parseInt(args[0])? [duplicate]

This question already has answers here:
String[] args parameter: java.lang.ArrayIndexOutOfBoundsException
(3 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I've seen below code in one of the video tutorial.There its executes fine but while I'm trying to execute in my system, it is compiling fine but I'm getting runtime error saying,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
class Test13
{
public static void main(String[] args)
{
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
}
Can someone please guide me what's wrong with this code and how to rectify?
Thanks in advance!
It looks you're not passing in any parameters when you run your code.
From the Java doc for ArrayIndexOutOfBoundsException: '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.'
Therefore you're trying to pull a value from the args array with an index 0, but the array is less than this size (in this case it's empty).
In order for this to prevent an exception being thrown you can apply a size check around the statement.
if(args.length>0) {
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
if (args.length > 0) {
Integer.parseInt(args[0])
}
ArrayIndexOutOfBoundsException occurs when you try to access an element at an index which does not exist in the array.
For example: suppose int a[]={2,4,5,10,3} is an array.
the size of array is 5 and index starts from 0.
Which means your array ranges from index 0 to index 4 where element at index 0 is the first element i.e. 2 and element at index 4 is the last element i.e. 3
if you try to access any elements at an index which is not in the range 0 to 4 it will show you ArrayIndexOutOfBoundsException because no such index exists in the array.
Now in your case args is command line argument which means you have to pass parameters when you run your code.
If you are running your code from terminal then after java yourclassname you have to pass parameters.
For example: java yourclassname 10 20 30
here 10 20 30 are your command line arguments which get stored in your args array and args[0]=10 args[1]=20 args[2]=30
If you haven't passed any arguments during running your code your args is empty and therefore you will get ArrayIndexOutOfBoundsException
hope it helps you to understand the concept of command line arguments.
You should pass an argument to your main method when executing your application.
For example, in command line type:
java Test13 123
Then the output should be:
123
Moreover you can check argument availability by check args.length, like what Adam said in prev answer.
You are not passing any argument while running your program. If you are running from command line then write java Test13 1. you will be able to get your result in output.
If you are using eclipse to run your program then provide your arguments in "Run Configuration" ->Arguments tab -> Program Arguments text box -> give value as 1.
You will be able to run your program
This is a runtime error as you might have observed the compilation goes smoothly. Now, why this happens is because you have to pass the "argument" while you give the run command (as in 2)
1. You might have run this command, without actually passing the argument [0]:
When you do this, the array is of length 0 as there are no arguments passed to the main function. Which is how the program is expected to run according to your code.
$ java Test13
This will give an error output. The one you got, with Array exception.
2. Try running this command, that is, type a number along with your command:
$ java Test13 727
Here, you are passing the argument [0] as 727 to the main function. Which adds the element to your array. This should work fine.
Similarly, suppose you have more arguments like [0], [1] and [2] And, you forget to add numbers after '727' like in command 2. You must get a similar error. Unless you do this (giving three inputs for your command):
$ java Test13 727 837 9
This means you need to give your input during the run command itself. However, in C++ with 'cin' in your code, you can give input after running the first command. Java is safer this way, although no real threat exists here.
Hope this works for you :)

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

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.

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

String conversion in java is throwing array index out of range exception

I have written following code but it is throwing array index out of range exception
String options = "" + args[0];
if (options.toLowerCase().contains("failover"))
{
dataToPass[0]= "failover";
callScript("Clus1toNfastfastsamehost",dataToPass);
}
Exceptions:
exception_name = java.lang.ArrayIndexOutOfBoundsException
exception_message = Array index out of range: 1
Well, Either you are not allocated enough memory the dataToPass[] or you have not pass arguments to the program. If no arguments is passed then args, it's a zero length array. Debugging will be a good option for you mate.
You are not passing an argument to your program.
Well, it's a straightforward exception. Check all your array lengths. How many items are in args? In dataToPass? Consider using a debugger.
UPDATE WITH CODE FIX
String options = ""
if (args.length > 0)
options += args[0]
Original comments:
There are two places you reference an array in the example code. args[0] and dataToPass[0]
It must be one of those two. So, a) you are not passing any arguments to the programs and args[0] is not defined -- this seems strange to me because I thought args[0] was the program name or b) dataToPass[0] was not allocated -- is dataToPass a zero length array and not a 1 length array?

Categories

Resources