My code sample:
public class arrray_2{
public static void main(String[] args) {
populateArray();
}
public static void populateArray(){
int [] numbers = new int [131071];
HashSet<Integer> used = new HashSet<Integer>();
for (int i = 0; i < 131071; i++) {
int num = (int)(Math.random() * 131072 );
while (used.contains(num)) {
num = (int) (Math.random() * 131072 );
}
used.add(num);
numbers[i] = num;
}
Arrays.sort(numbers);
for (int element : numbers) {
System.out.println(numbers[element]);
}
for (int x = 0; x < numbers.length; x++) {
if (numbers[x]+1 != numbers[x+1] ) {
System.out.println("Missing Number is: "+numbers[x]);
}
}
System.out.println("hi");
}
}
By executing this I come up with this error:
java.lang.ArrayIndexOutOfBoundsException
This is my code I'm using and for some reason, the code after the for (int : element) is being ignored and I don't know why.
ERROR
You have a logic error to the last for the statement. You are saying:
if (numbers[x]+1 != numbers[x+1] )
The numbers length is 131071. By saying numbers[x+1] means that it will try to compare the position of 131071+1 = 131072 something that is out of bounds. Do you see the error? You said in the beginning that you want an array of 131071 positions and you try to compare for the 131072nd something that does not exist.
TIP
You must replace also this:
System.out.println(numbers[element]);
with this:
System.out.println(element);
That is why you use this kind of for statement. Otherwise, you need to use the classic/default one.
SOLUTION
You are missing a +1 in your if statement. Insert it and it will be fixed.
First, I have an array which is filled with 0's except for position 5, which is filled with "a" (put there intentionally to throw an NumberFormatException).
And then I call testMethod passing the array, the size of the array, and how many Callables there will be.
In this example the array has a size of 10, and there are 4 callables.. the array is processed in chunks:
First chunk is positions 0 and 1
Second chunk is positions 2 and 3
Third chunk is positions 4 and 5
Fourth chunk is positions 6 and 7
Fifth chunk is positions 8 and 9
Sixth chunk is position 10
I need to find out which position the NumberFormatException occurs, or in a more general sense: I need to know what the position is when any exception occurs.
So I can print out in the message "Execution exception occurred at position 5"
I'm quite new to using ExceutorService/Callables so I'm not quite sure how to achieve this...
And if it's impossible to achieve using my current set up... is there a similar way to do this parallel processing that will also give me the ability to find the position where the exception occurred?
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThreadTest {
private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>();
private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception {
/*Fill the array with 0's, except for position 5 which is a letter and will throw number format exception*/
final String[] nums = new String[10];
for (int i = 0; i < 5; i++) {
nums[i] = "0";
}
nums[5] = "a";
for (int i = 6; i < nums.length; i++) {
nums[i] = "0";
}
testMethod(nums, 10, 4);
}
static void testMethod(String[] nums, int size, int processors) throws Exception {
mCallables.clear();
int chunk = (size / processors) == 0 ? size : size / processors;
System.out.println("Chunk size: "+chunk);
for (int low = 0; low < size; low += chunk) {
final int start = low;
final int end = Math.min(size, low + chunk);
mCallables.add(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
System.out.println("New call");
for (int pos = start; pos < end; pos++) {
System.out.println("Pos is " + pos);
System.out.println("Num is " + nums[pos]);
double d = Double.parseDouble(nums[pos]);
} //end inner loop
return true;
} //end call method
}); //end callable anonymous class
}
try {
List<Future<Boolean>> f = mExecutor.invokeAll(mCallables);
for (int i = 0; i < f.size(); i++) {
f.get(i).get();
}
} catch (ExecutionException e) {
String s = e.toString();
System.out.println(s);
System.out.println("Execution exception"); //need to write here which pos the numberFormat exception occurred
}
mExecutor.shutdown();
}
}
Can't you add a try/catch over the Double.parseDouble line and throw an exception which includes the position ?
Can anyone answer this question?
public class AddingArray {
public static void main(String[] args){
int arry1[] = {2,3,4,5,6,7,9};
int arry2[] = {4,3,7,9,3,5};
for(int i = 0; i <arry1.length; i++){
int result = arry1[i] + arry2[i];
System.out.println("Result "+result);
}
}
}
Whenever I try executing the above code I get the error Exception in
thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at
basics.AddingArray.main(AddingArray.java:9)
But,my output should be like this 6,6,11,14,9,12,9
As people have mentioned, one of yours arrays is literally shorter than the other. Take two blocks and overlay them over only one block. The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.
I would make sure both of them are of the same size. If you do want to leave em as they are, I would do this:
int result = 0;
try
{
for(int i = 0, length = array2.length; i < length; i++)
{
result = array1[i] + array2[i];
System.out.println("Result is: " + result);
}
catch(Exception e)
{
System.out.println("You tried to do something that resulted in an error");
System.out.println("Your previous result was: " + result);
}
}
SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.
Let's make this as simple and understandable as possible, with no fancy annotations:
You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums. However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
You need to determine the length of the longest array. You can do this with a Math.max()-method, where you give the length of each array as parameters:
int biggestArrayLength = Math.max(arry1.length, arry2.length);
Then, instead of for(int i=0;i<arry1.length;i++){, you write:
for(int i=0;i<biggestArrayLength;i++){
Now it doesn't matter which of the two arrays is the biggest one.
Inside the loop, I would define two ints, representing a value from each of the two arrays:
int value1 = arry1[i];
int value2 = arry2[i];
however, this will give an error when the smallest array does not have any more elements. We need to check if the array actually has an element with index i. index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6. In other words, only index numbers that are lower (and not equal) to length, is valid numbers:
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
System.out.println("Result "+result);
}
}
}
Now, if you need to put these in a third array, say named sumArray, this would be the complete code:
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int biggestArrayLength = Math.max(arry1.length, arry2.length);
int[] sumArray = new int[biggestArrayLength];
for(int i=0;i<biggestArrayLength;i++){
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
sumArray[i] = result;
System.out.println("Result "+result);
}
}
}
It is because your loop will go from 0 to 6 (which is the array1.length - 1) and your array2 only has 6 elements (so from 0 to 5).
So when you are accessing arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException.
You could change your for loop to go to the length of the smallest array:
for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }
Or add an element in array2, but that is yours to decide since I do not know your requirements.
Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.
either do:
if(arry2[i] != null) {
//run your adding code
}
or change your arrays to be the same size
Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop. This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException.
Can we stop the downvoting?
End edit----
If you want to add up all of the elements in the array use this code.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result+=arry1[i];
}
for(int j=0; j < array2.length; j++){
result += array2[j];
}
System.out.println("Result: "+ result);
}
}
if you are trying to sum individual elements as you loop you can do the following. This will properly handle 2 arrays of different length regardless of which one is longer.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result=arry1[i];
if(i < array2.length){
result += array2[i];
}
System.out.println("Result: "+ result);
}
for(int j = i; j < array2.length; j++){
System.out.println("Result: "+ array2[j]);
}
}
}
I have to create an array size of 10 and generate random numbers from 0 to 100 including 0 and excluding 100. When I write the code it keeps giving me an error of:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 59
at BillyLancasterHw6.printArray(BillyLancasterHw6.java:23)
at BillyLancasterHw6.main(BillyLancasterHw6.java:13)
Here is the code I am using.
public class BillyLancasterHw6 {
public static void main(String[] args){
//int N = 10;
double[] list = new double[10];
for(int i = 0; i < list.length; i++) {
double randomNumber = (Math.random() * 100);
list[i] = randomNumber;
}
printArray(list);
//sort(list);
//System.out.println();
//printArray(list);
}
public static void printArray(double[] list) {
for(double u: list) {
System.out.printf("%2.2f%s", list[(int) u], " ");
}
}
}
I am not understanding why I cannot generate random numbers up to 100 in an array of size 10. Meaning that 10 numbers are randomly generated between 0 and 100.
Any suggestions would be great. If you can reference where in the documentation I can find the answers as well. I am new to programming and am having trouble with this.
Your enhanced for loop has already done the job of extracting the random number for you out of the list; just print it. There's no need to go back to the list.
System.out.printf("%2.2f%s", u, " ");
I'm a bit rusty on my java but:
for(double u: list) {
System.out.printf("%2.2f%s", list[(int) u], " ");
}
looks suspicious. What about this:
for(double u: list) {
System.out.printf("%2.2f%s", u, " ");
}
Maybe I'm not getting your question but see if the code below work's. I don't understand why your using double
public class BillyLancasterHw6 {
public static void main(String[] args)
{
int[] randomNumber = new int[10];
for(int i = 0; i < randomNumber.length; i++)
{
randomNumber[i] = (int)(Math.random() * 100);
System.out.print(randomNumber[i]+" , ");
}
System.out.println();
}
}
I trying to solve this insertion sort problem (not the exact insertion sort)and wrote the following code:
import java.util.*;
public class Solution {
static void insertionSort(int[] ar,int n) {
int key=ar[n];
int temp;
int j=1;
for(int i=0;i<ar.length;i++){
j++;
}
for(int i=j-1;i>=0;i--){
temp=ar[i];
if(temp>key)
{
ar[i+1]=temp;
printArray(ar);
}
else{
ar[i+1]=key;
printArray(ar);
}
}
}
/* Tail starts here */
static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i=0;i<n;i++){
ar[i]=in.nextInt();
}
insertionSort(ar,n);
}
}
But I'm getting an error as an array out-of-bound exception, and I could not figure out where it went wrong. The error message is posted below. How should I fix this?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Solution.insertionSort(Solution.java:9)
at Solution.main(Solution.java:49)
As Brian points out, the first line isn't going to work because you have
int key=ar[n];
and n is ar.length (which makes it redundant in this case as well)
Using a debugger would show you the error, but I suspect the problem is here
ar[i+1]=temp;
as i assume i is the last valid reference.
BTW
int j=1;
for(int i=0;i<ar.length;i++){
j++;
}
is the same as
int j = 1 + ar.length;
Again, this would make j or j-1 too large to index in the array.
ArrayIndexOutOfBoundException like mentioned above occurs when you try to access a position which doesn't exist.
You have passed your insertSort() function the size of array. I dont think you need a j variable.
by your implementation:
j = ar.length + 1 = n + 1;
For eg:
n = 5
ar = 3, 6, 2, 7, 3
^ ^ ^ ^ ^
index:0, 1, 2, 3, 4
j = n+1 = 6
When you loop your array from i=j-1;
temp=ar[i]; -> ar[5]
ar[i+1]=key; or ar[i+1]=temp; -> ar[6]
both positions that you tried to access above are illegal - hence the error
your for loop should be something like:
for(int i=n-2; i>=0; i--)
First thing first, can you name your variables something other than 'i', 'j' and 'n'?
Then once you have done that, use a consistent style throughout your code (You have dropped some braces and not others?).
Then,..once you can read the code easily, use the debugger, and find out which line you are going our of bounds on. You may find this useful: http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
This is line #49. That means at that point, you try to access a position in the array which does not exist. Your array is of size 'n' currently (name this properly!). You are trying to get position n here:
int key=ar[n];
The array you have goes from 0 to n-1. For example, if n was 5, you have ar[0], ar[1], ar[2], ar[3] and ar[4]. That is 5 positions, so ar[5] (or ar[n]) does not exist.
i found the answer as
/* Head ends here */
import java.util.*;
public class Solution {
static void insertionSort(int[] ar,int n) {
int key=ar[n-1];
int temp;
int inserted=0;
for(int i=ar.length-2;i>-1;i--){
temp=ar[i];
if(temp>key)
{
ar[i+1]=temp;
printArray(ar);
}
else {
ar[i+1]=key;
inserted=1;
break;
}
}
if(inserted==0){
ar[0]=key;
}
printArray(ar);
}
/* Tail starts here */
static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i=0;i<n;i++){
ar[i]=in.nextInt();
}
insertionSort(ar,n);
}
}