I'm making a program where I calculate a random number using a function named generarAleatorio.
public static int generarAleatorio(int l){
java.util.Random X = new java.util.Random();
return X.nextInt(l) ;
}
Then, I use that number to locate a value inside an array using the length of the array as the parameter for the generarAleatorio parameter
public static String generarFecha(){
int[] dias={1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30};
int[] mes={1,2,3,4,5,6,7,8,9,10,11,12};
return String.format("%d-%d",dias[generarAleatorio(dias.length)],
mes[generarAleatorio(generarAleatorio(mes.length))]);
}
The problem is that sometimes an Exception is showed that looks like this
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at generadorregistros.GeneradorRegistros.generarAleatorio(GeneradorRegistros.java:70)
at generadorregistros.GeneradorRegistros.generarFecha(GeneradorRegistros.java:108)
at generadorregistros.GeneradorRegistros.main(GeneradorRegistros.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
It tells me that the Bound im sending its not positive, but as far as I know, the length of the Array is always the same and also positive.
What's the cause of this? Is the length of the array not always positive?
Is the length of the array not always positive?
It is in your case. However, the problematic call doesn't use the array length but a random number:
generarAleatorio( generarAleatorio(mes.length) )
Here the inner generarAleatorio(mes.length) may return 0 in which case the outer generarAleatorio(0) fails.
How to fix the problem depends on what you want to do. Both of the following changes would make the error go away -- but the behavior of your program will be very different.
mes[generarAleatorio(generarAleatorio(mes.length)+1)]
mes[generarAleatorio(mes.length)]
Related
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 :)
This question already has answers here:
Why is "out of range" not thrown for 'substring(startIndex, endIndex)'
(6 answers)
Closed 4 years ago.
I apologize if title is not clear.
Now, in strings index starts at 0. So for instance:
Index 0 1 2 3 4
String H E L L O
In this case, the last index is 4.
If I would try to do something like this:
System.out.println("hello".charAt(5));
It would throw an 'Index Out Of Bounds Exception', as it should.
However, if I try to run the following code:
System.out.println("hello".substring(5));
It does run! I wrote similar code, noticed this later and could not figure it out.
Eventually, the question is that how is this possible that we can reach this index we should not? It allows us to write:
stringObj.substring(stringObj.length());
and it doesn't look very safe as stringObj.length() return us an integer that is one more than what the last index is.
Is it made intentionally and does this have a purpose? If so, what is this purpose and what is the benefit it brings?
It is easier to work with substring when you think of indexes like this (like letters are between indexes)
H E L L O
0 1 2 3 4 5 <- acceptable range of indexes for "HELLO"
^ ^
| |
start end = length
(min index) (max index)
When you substring from start to end you get only characters between these indexes.
So in case of "HELLO".substring(2,4) you will get part
L L
2 3 4
which returns "LL".
Now in case of substring(5) it acts same as substring(5,length) which means in this case it is substring(5,5). So since 5 index exists in our "model" as acceptable value, and since there are no characters between 5 and 5 we are getting empty string as result.
Similar situation happens in case of substring(0,0) substring(1,1) and so on as long as indexes are acceptable by our model.
StringIndexOutOfBoundsException happens only when we try to access indexes which are not acceptable, which means:
negative ones: -1, -2, ...
greater than length. Here: 6 7, ...
It would not compile due to 'Index Out Of Bounds Exception',
It does compile. You get a runtime Exception when you try to execute the code.
System.out.println("hello".substring(5));
Eventually, the question is that how is this possible that we can reach this index we should not?
Read the API for the substring(...) method. It explains how the method works and what the parameter means.
In this case it returns an empty String.
Refer to the substring method at Java String API
(http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))
A String ".length()" method will return the number of characters in the string.
if you count "HELLO" from 0->4, it will still amount to 5 characters (the length), which is the number returned when you call "Hello".length().
If you want to access the last character of a String, use (Stringobj.length()-1); Accessing the last element of a String or Array through utilizing its .length() or .size() method calls is standardized across Java.
In this case details of implementation of methods charAt and substring are helpful to know.
charAt as described in this tutorial can be described as method that:
returns the character located at the String's specified index. The string indexes start from zero.
That is why calling:
System.out.println("hello".charAt(5));
gives
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 5
Because maximum index is, as you perfectly described, only 4.
substring is described in java documentation and explains your exact situation here in the "Examples" section which states that :
"emptiness".substring(9) returns "" (an empty string)
For additional reference, here is the source code for java's substring(int index) implementation, where you can see that it uses java's substring(int beginInndex, int endIndex) method.
I'm creating an Android app, and I'm reading some coordinates from a text file.
I'm using Integer.parseInt(xCoordinateStringFromFile) to convert the X coordinates to integers, and in the same way with the Y coordinates.
When I run the app, I get an error on that line, which looks like this:
BridgeData data = new BridgeData(
elements[0],
elements[1],
Integer.parseInt(elements[2]),
Integer.parseInt(elements[3]),
Integer.parseInt(elements[4]),
new GeoPos(Integer.parseInt(elements[5].split(",")[0]), Integer.parseInt(elements[5].split(",")[1])),
new GeoPos(Integer.parseInt(elements[6].split(",")[0]), Integer.parseInt(elements[6].split(",")[1])),
Integer.parseInt(elements[7]),
Integer.parseInt(elements[8])
);
The variable elements is a String array created by splitting the current line on every ;.
The "main" error is:
java.lang.NumberFormatException: Invalid int: "3546504756"
I wonder what this means, and how I can solve it.
Error just means that java is not able to convert the String that you are trying to use in your call to Integer.pasrseInt as that number is out of range of an integer.
You should be using Long.parseLong as 3546504756 number is out of range of an integer.
Make sure post that your BridgeData constructor accepts long as a parameter instead of integer.
Revising the concept of data type and their size might help you
http://www.tutorialspoint.com/java/java_basic_datatypes.htm
In Java, an int is 32 bits, which is enough to store numbers up to just over 2 billion. The number you were trying to read was an invalid int because it was too big.
I would seriously question the design of whatever you are doing, if you have coordinates with values of over a billion. But if you really need such big numbers, use long in place of int in your BridgeData class, and Long.parseLong in place of Integer.parseInt in the code that you quoted.
The range of int value can be lies between -2,147,483,648 to 2,147,483,647 and you are providing it more than that thats why it giving numberformatexception
You have to store the value in either long or other more range premetive type.
You can find more about java premetive data type range and value here
We've tried using the MillerUpdatingRegression class in one of our projects and ran into an issue. After creating an instance of the class, providing the number of variables to expect and adding observations from the entire sample set, we call the "regress(int[])" method, informing the regression process which variables we'd like to include (a subset of the entire predictor set).
When we do this, we receive an ArrayIndexOutOfBounds exception during the process because the number of variables to expect (nvars, provided when the MillerUpdatingRegression class was instantiated) is less than the number of variables passed to the "regress(int[])" method. Our understanding was that this array of integers could be a subset of the predictor indices from all observations.
Does anyone know what we're missing here?
==== Updated with Code ====
double predictorData[][] = new double[n][125];
double predictions[] = new double[n];
//predictorData is a [n x 125] two-dimensional array of
//features/predictors with n samples and 125 predictors
//predictionsArray is a n-length array of predictions
//for the sample set
int numberOfPredictorVariables = 125;
boolean includeConstantWhenBuildingModel = true;
MillerUpdatingRegression regression = new MillerUpdatingRegression(numberOfPredictorVariables,includeConstantWhenBuildingModel);
regression.addObservations(predictorData,predictionsArray)
int predictorsToIncludeInRegression[] = {0,3,9,11};
regression.regress(predictorsToIncludeInRegression);
//this is where the ArrayIndexOutOfBounds exception is generated
I can just guess here without a complete code example, but the number of observations must must be larger than the number of variables (which is 125 in your example).
To be more precisely, the n in your code must be larger than 125 for for the regression to work. The number of predictors passed into the regress method can be less than that.
Each object in my warehouseList contains a end stock, safety stock, and a required stock.
My aim to change the end stock of an object if lesser that 10% of the safety stock, and put it in range of -%10 to %5 of the safety stock. To do this im using a randomizer code:
Random random=new Random();
for(Warehouse obj:warehouseList){
double diff=obj.getEndStock()-obj.getSafetyStock();
if(((diff/obj.getSafetyStock())*100)<(-5)){
diff=Math.abs(diff)+(1.05*obj.getSafetyStock())-obj.getSafetyStock();
if(diff<0)
Logging.log(diff,"\n");
int randomNum=0;
double reqStock=0;
double end=obj.getEndStock();
while(((end-obj.getSafetyStock())*100)<(-5)){
randomNum=random.nextInt((int)diff);
reqStock+=randomNum;
end+=randomNum;
}
obj.setRequiredStock(reqStock);
obj.setEndStock(end);
}
}
}
Now to the problem: I'm checking if the diff variable even becomes negative as it doesnt as nothing prints on the console, However whenever i reach the the line randomNum=random.nextInt((int)diff);
the program throws the following error:
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Unknown Source)
at managing.Final.randomWay(Final.java:163)
at managing.Final.main(Final.java:252)
CAN ANYONE HELP?
This is rather simple. Look at these two lines:
double diff=obj.getEndStock()-obj.getSafetyStock();
...
randomNum=random.nextInt((int)diff);
Your diff contains a difference between end stock and safety stock. If your end stock is below safety stock, then diff will contain a negative number.
nextInt method requires a positive integer as a parameter. If your diff is negative, you'll get this error.
EDIT: In response to the comment I re-read the question carefully again and noticed the line I missed. With this line:
diff=Math.abs(diff)+(1.05*obj.getSafetyStock())-obj.getSafetyStock();
You actually can get a 0. (I am assuming that your getSafetyStock would always return a positive number - if it doesn't, then this may be your problem.)
In your code, you are checking whether diff is 0 - but are not doing anything about it, other than printing a log line.
On the whole, it may make sense to print the value of diff regardless of what it is before using it as a parameter for nextInt - for debugging purposes.
I see no check for negative value. Here:
if(diff==0)
Logging.log(diff,"\n");
You check for zero-equality, which is weird for double-typed variable anyway.
It seems I get what's wrong. nextInt method requires it's argument to be positive, but you are checking if it is non-negative. That's what causes the error.
This code prooves my point:
import java.util.Random;
public class RandomMain {
public static void main(String[] args) {
Random random = new Random();
System.out.println(random.nextInt(0));
}
}
it generates an exception:
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300)
at RandomMain.main(RandomMain.java:6)