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 ?
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 months ago.
Improve this question
DISCLAIMER This problem is part of a COMPLETED competition and will not be reused
I was hoping someone could create and explain a solution efficient enough to run file sizes at most 15 x 15 tiles. Below is the problem:
Tiled Floor (40 points)
Sam recently hired a tile installer to tile a kitchen floor. The floor was supposed to be very colorful with no two
adjacent tiles having the same color. Unfortunately, the installer failed to ensure adjacent tiles have different
colors. The mortar is still wet, but it is difficult to lift just one tile at a time, so the installer is limited to swapping
adjacent tiles. The question is how to exchange adjacent tiles in as few moves as possible so that the floor meets
the criteria that no two adjacent tiles have the same color.
A sample input is
RGR
RPC
GRB
YPG
Representing the tiles on a three by four floor where R is a red tile, G is green, B is blue, C is cyan, P is purple, and
Y is yellow. In general, the input will be a series of lines of R, G, B, C, P, and Y. Each line will have the same length
and there will be a maximum of 15 lines with 15 characters in each line. The output is to be an integer
representing the number of swaps of adjacent tiles. For this problem, “adjacent” means touching and in the same
row or column; for example, the only two tiles are adjacent to the yellow tile in the lower left corner of the above
floor: the green tile at the start of the third row and the purple tile in the middle of the fourth row.
The output for the above floor will be
2
since the red tile at the start of row 2 can be swapped with the green tile at the start of row three, and then the
red tile in middle of row 3 can be swapped with the blue tile at the end. This gives the arrangement
RGR
GPC
RBR
YPG
Other fixes are possible such as exchanging the first two tiles on row 2 to get PRC and then exchanging the middle
tiles in rows 3 and 4. Your program does not print the resulting floor arrangement, just the minimum number of
tile swaps that must take place. Sometimes it is not possible to fix a floor:
GGYGP
CGGRG
This isn’t possible to tile because there are 6 Gs and a floor this size can fit only 5 without two being adjacent. In
cases where there is no solution, the output is to be
not possible
I have created a solution but it works only for approximately 16 tiles (4 x 4), any more takes an enormous amount of time. This is because of the recursive and naive nature of this function, for every call it calls itself at least 4 times.
Below is my attempted solution, keep in mind that there are extra methods from previous attempts and that minimumSwaps() is the main recursive method:
import java.util.*;
import java.io.*;
class Main {
private static ArrayList<String[][]> solutions = new ArrayList<String[][]>();
private static ArrayList<Integer> moves = new ArrayList<Integer>();
private static int min = Integer.MAX_VALUE;
public static void main(String[] args) throws Exception {
File file = new File("Tiles.txt");
Scanner scan = new Scanner(file);
Scanner scan1 = new Scanner(file);
int length = 0;
while (scan1.hasNextLine()) {
scan1.nextLine();
length++;
}
String[][] tiles = new String[length][];
for (int i = 0; i < length; i++) {
String line = scan.nextLine();
tiles[i] = new String[line.length()];
for (int l = 0; l < tiles[i].length; l++) {
tiles[i][l] = line.substring(l, l + 1);
}
}
System.out.println("Start");
minimumSwaps(tiles, 0, new ArrayList<String>());
//System.out.println(Arrays.toString(findCount(tiles)));
//findSolutions(new String[tiles.length][tiles[0].length], findCount(tiles), 0, 0);
//System.out.println(solutions.size());
System.out.println(min);
//display();
}
//tilesIDs: more efficient way to check if computer has seen previous situation
//how to know if there are moves that do not involve problem areas that reduces total number of moves?
public static void minimumSwaps (String[][] tiles, int moves, ArrayList<String> tilesIDs) {
if (moves < min) {
String newID = computeID(tiles);
if (linearSearch(tilesIDs, newID)) return;
tilesIDs.add(newID);
if (solved(tiles)) {
//Main.moves.add(moves);
if (moves < min) min = moves;
//solutions.add(cloneTiles(tiles));
}
else if (moves < min - 1) {
for (int i = 0; i < tiles.length; i++) {
for (int l = 0; l < tiles[i].length; l++) {
if (adjacentPresent(tiles, tiles[i][l], i, l)) {
try {
String[][] newTiles = cloneTiles(tiles);
String current = newTiles[i][l];
newTiles[i][l] = newTiles[i][l - 1];
newTiles[i][l - 1] = current;
minimumSwaps(newTiles, moves + 1, (ArrayList<String>)(tilesIDs.clone()));
}
catch (Exception e) {}
try {
String[][] newTiles = cloneTiles(tiles);
String current = newTiles[i][l];
newTiles[i][l] = newTiles[i][l + 1];
newTiles[i][l + 1] = current;
minimumSwaps(newTiles, moves + 1, (ArrayList<String>)(tilesIDs.clone()));
}
catch (Exception e) {}
try {
String[][] newTiles = cloneTiles(tiles);
String current = newTiles[i][l];
newTiles[i][l] = newTiles[i - 1][l];
newTiles[i - 1][l] = current;
minimumSwaps(newTiles, moves + 1, (ArrayList<String>)(tilesIDs.clone()));
}
catch (Exception e) {}
try {
String[][] newTiles = cloneTiles(tiles);
String current = newTiles[i][l];
newTiles[i][l] = newTiles[i + 1][l];
newTiles[i + 1][l] = current;
minimumSwaps(newTiles, moves + 1, (ArrayList<String>)(tilesIDs.clone()));
}
catch (Exception e) {}
}
}
}
}
}
}
public static boolean linearSearch(ArrayList<String> IDs, String newID) {
for (String ID : IDs) if (ID.equals(newID)) return true;
return false;
}
public static String computeID(String[][] tiles) {
String ID = "";
for (String[] letters : tiles) {
for (String letter : letters) {
ID += letter;
}
}
return ID;
}
public static String[][] cloneTiles(String[][] tiles) {
String[][] newTiles = new String[tiles.length][tiles[0].length];
for (int i = 0; i < tiles.length; i++) {
newTiles[i] = tiles[i].clone();
}
return newTiles;
}
public static boolean solved(String[][] tiles) {
for (int i = 0; i < tiles.length; i++) {
for (int l = 0; l < tiles[i].length; l++) {
if (adjacentPresent(tiles, tiles[i][l], i, l)) return false;
}
}
return true;
}
public static int minMoves() {
int min = Integer.MAX_VALUE;
for (int num : moves) if (num < min) min = num;
return min;
}
public static void findSolutions(String[][] tiles, int[] count, int i, int l) {
String[] colors = {"R", "G", "B", "C", "P", "Y"};
for (int z = 0; z < 6; z++) {
//System.out.println("testing");
if (!adjacentPresent(tiles, colors[z], i, l) && count[z] > 0) {
String[][] newTiles = new String[tiles.length][tiles[0].length];
for (int a = 0; a < newTiles.length; a++) {
for (int b = 0; b < newTiles[0].length; b++) {
newTiles[a][b] = tiles[a][b]; // clone does not work properly?
}
}
newTiles[i][l] = colors[z];
//System.out.println(Arrays.deepToString(newTiles));
int[] newCount = count.clone();
newCount[z]--;
if (l == tiles[0].length - 1 && i != tiles.length - 1) {
findSolutions(newTiles, newCount, i + 1, 0);
}
else if (l < tiles[0].length - 1) {
findSolutions(newTiles, newCount, i, l + 1);
}
else if (l == tiles[0].length - 1 && i == tiles.length - 1) {
solutions.add(newTiles);
}
}
}
}
public static boolean adjacentPresent(String[][] tiles, String color, int i, int l) {
try {
if (tiles[i][l + 1].equals(color)) return true;
}
catch (Exception e) {}
try {
if (tiles[i][l - 1].equals(color)) return true;
}
catch (Exception e) {}
try {
if (tiles[i + 1][l].equals(color)) return true;
}
catch (Exception e) {}
try {
if (tiles[i - 1][l].equals(color)) return true;
}
catch (Exception e) {}
return false;
}
public static int[] findCount(String[][] tiles) {
int[] count = new int[6];
for (String[] line : tiles) {
for (String letter : line) {
switch (letter) {
case "R": count[0]++;
break;
case "G": count[1]++;
break;
case "B": count[2]++;
break;
case "C": count[3]++;
break;
case "P": count[4]++;
break;
case "Y": count[5]++;
break;
}
}
}
return count;
}
public static void display() {
for (String[][] lines : solutions) {
for (String[] line : lines) {
for (String letter : line) {
System.out.print(letter);
}
System.out.println();
}
System.out.println("\n\n");
}
}
}
Improving the algorithm
A breadth-first search would yield, as first result, an optimal solution. It could still be slow on larger problems where the solution is deeper in; or in the worst case, when there is no solution at all.
Your current algorithm looks like backtracking, which is depth-first, and therefore you need to look at all possible solutions before being sure you have found the shortest one. This is very wasteful.
Improving the data representation
You have 6 colors in a 15x15 grid. You are currently storing up to 15x15=225 strings, and constantly copying that String[][] over. It would be a lot more efficient to use a single byte[] (of length dim x dim), which can be copied over faster. Use integers (1, 2, ...) instead of color-chars ("R", "Y", ...). With a single dimension you have to do some math to check for adjacency, but it is nothing too fancy; and you win a lot of memory locality.
I'm trying to learn a bit Java with tutorials and currently I'm struggling with piece of code where I should find on which index is difference between arrays (if there is difference at all)
My code
Scanner scanner = new Scanner(System.in);
int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int sumArrOne = 0;
int index = 0;
boolean diff = false;
for (int k : arrOne) {
if (Arrays.equals(arrOne, arrTwo)) {
sumArrOne += k;
} else {
for (int i : arrTwo) {
if (k != i) {
index = i;
diff = true;
break;
}
}
}
}
if (diff) {
System.out.println("Found difference at " + index + " index.");
} else {
System.out.println("Sum: " + sumArrOne);
}
So, if arrays are identical I'm sum array elements in arrOne. If they are not identical -> must show at which index they are not.
With this code when I input
1 2 3 4 5
1 2 4 3 5
I should get that difference is at index 2 instead I've got index 1.
I'm not quite sure why and would be glad if someone point me out where is my mistake.
I updated your code. Looks like you're misunderstanding the concept of indexes yet.
Use one common index to check with in both arrays, in my example it's simply called i:
import java.util.Arrays;
import java.util.Scanner;
public class BadArray {
static private final int INVALID_INDEX = Integer.MIN_VALUE;
public static void main(final String[] args) {
try (final Scanner scanner = new Scanner(System.in);) {
final int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
final int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int sumArrOne = 0;
int diffIndex = INVALID_INDEX;
final int minLen = Math.min(arrOne.length, arrTwo.length);
for (int i = 0; i < minLen; i++) {
sumArrOne += arrOne[i];
if (arrOne[i] != arrTwo[i]) {
diffIndex = i;
break;
}
}
if (diffIndex != INVALID_INDEX) {
System.out.println("Found difference at " + diffIndex + " index.");
} else if (arrOne.length != arrTwo.length) {
System.out.println("Arrays are equal but have different length!");
} else {
System.out.println("Sum: " + sumArrOne);
}
}
}
}
I also put the scanner into a try-resource-catch to handle resource releasing properly.
Note you could also do the array lengths comparison right at the start if different array lengths play a more crucial role.
You are trying to find out which index has the first difference so you should iterate via the index rather than using a for-each loop (aka enhanced for loop). The following method should work for this.
/**
* Returns the index of the first element of the two arrays that are not the same.
* Returns -1 if both arrays have the same values in the same order.
* #param left an int[]
* #param right an int[]
* #return index of difference or -1 if none
*/
public int findIndexOfDifference(int[] left, int[] right) {
// short-circuit if we're comparing an array against itself
if (left == right) return -1;
for (int index = 0 ; index < left.length && index < right.length ; ++index) {
if (left[index] != right[index]) {
return index;
}
}
return -1;
}
In your code you compare, where the indexes are different, not the values at the indexes. Also your code has several other issues. I'll try to go through them step by step:
// compare the whole array only once, not inside a loop:
diff = !Arrays.equals(arrOne, arrTwo));
if (!diff) {
// do the summing without a loop
sumArrOne = Arrays.stream(arrOne).sum();
} else {
// find the difference
// it could be the length
index = Math.min(arrOne.length, arrTwo.length);
// or in some different values
for (int i = 0; i < index; i++) { // do a loop with counter
if (arrOne[i] != arrTwo[i]) {
index = i;
break;
}
}
}
It doesn't matter that I set index here above the loop as it's value will be overwritten anyways inside the loop, if relevant.
I am not sure if it's rly possible to check but I have an issue rn where I have an array
let's say: int[] unmarkedSum = new int[100];
Now I put something in this array when a certain condition is true so not in every single iteration. But I know for a fact that at some point the whole array will be filled with any positive values that are not 0 because of how my algorithm works.
My question here is: Is there a way of checking WHEN it's fully filled?
Like I started like this:
for(int i = 0; i < unmarkedSum.length; i++) {
if(unmarkedSum[i] == 0 {
break;
}
else {
// idk tbh
}
}
In Java by default an array of ints is filled with zeros. You can use this to check if the array is fully filled. For example you can create a method which checks for 0 and returns true if there are no 0:
public static bool isArrayFilled(int[] array) {
for(int i = array.length; i >= 0; i--){
if(array[i] == 0) {
return false;
}
}
return true;
}
If array is big enough and filled out of order, you can use advanced algorithms to find at least one 0 value in the array.
I would simply maintain a variable size that keep tracks of how many values have been written to the array.
Example:
int size = 0;
int[] array = new int[100];
Random r = new Random();
while(size < array.length){
int index = r.nextInt(100);
int val = r.nextInt(1000)+500;
if (array[index] == 0){
array[index] = val;
size++;
}
}
System.out.println(Arrays.toString(array));
Per my previous comment, you can share this array with another thread so that one thread can fill the values and another can check the array at the same time. When the second thread finds that there are no default values (or 0s) then it can notify the first thread (or the main thread). Here is how you can do that
import java.util.Arrays;
import java.util.Random;
public class CheckArray {
public static void main(String[] args) throws InterruptedException {
var arr = new int[50];
Thread arrayChecker = new Thread(() -> {
var isZeroPresent = false;
while (true) {
for (int index = 0; index < arr.length; index++) {
isZeroPresent = false;
if (arr[index] == 0) {
isZeroPresent = true;
break;
}
}
if (isZeroPresent == false) {
// if the for loop completed then control will come here
System.out.println("Array has been filled");
System.out.println(Arrays.toString(arr));
System.exit(0);
}
}
});
arrayChecker.start();
// fill random values in the array
// while another thread has been started
Random random = new Random();
while(true) {
Thread.sleep(500);
int index = random.nextInt(arr.length);
arr[index] = random.nextInt(100);
System.out.println(Arrays.toString(arr));
}
}
}
The longest increasing subsequence is the well known problem and I have a solution with the patience algorithm.
Problem is, my solution gives me the "Best longest increasing sequence" instead of the First longest increasing sequence that appears.
The difference is that some of the members of the sequence are larger numbers in the first(but the sequence length is exactly the same).
Getting the first sequence is turning out to be quite harder than expected, because having the best sequence doesn't easily translate into having the first sequence.
I've thought of doing my algorithm then finding the first sequence of length N, but not sure how to.
So, how would you find the First longest increasing subsequence from a sequence of random integers?
My code snippet:
public static void main (String[] args) throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int inputInt;
int[] intArr;
try {
String input = br.readLine().trim();
inputInt = Integer.parseInt(input);
String inputArr = br.readLine().trim();
intArr = Arrays.stream(inputArr.split(" ")).mapToInt(Integer::parseInt).toArray();
} catch (NumberFormatException e) {
System.out.println("Could not parse integers.");
return;
}
if(inputInt != intArr.length) {
System.out.println("Invalid number of arguments.");
return;
}
ArrayList<ArrayList<Integer>> sequences = new ArrayList<ArrayList<Integer>>();
int sequenceCount = 1;
sequences.add(new ArrayList<Integer>());
sequences.get(0).add(0);
for(int i = 1; i < intArr.length; i++) {
for(int j = 0; j < sequenceCount; j++) {
if(intArr[i] <= intArr[sequences.get(j).get(sequences.get(j).size() - 1)]) {
sequences.get(j).remove(sequences.get(j).size() - 1);
sequences.get(j).add(i);
break;
} else if (j + 1 == sequenceCount) {
sequences.add(new ArrayList<Integer>(sequences.get(j)));
sequences.get(j + 1).add(i);
sequenceCount++;
break; //increasing sequenceCount causes infinite loop
} else if(intArr[i] < intArr[sequences.get(j + 1).get(sequences.get(j + 1).size() - 1)]) {
sequences.set(j+ 1, new ArrayList<Integer>(sequences.get(j)));
sequences.get(j+ 1).add(i);
break;
}
}
}
int bestSequenceLength = sequenceCount;
ArrayList<Integer> bestIndexes = new ArrayList<Integer>(sequences.get(bestSequenceLength - 1));
//build bestSequence, then after it I'm supposed to find the first one instead
int[] bestSequence = Arrays.stream(bestIndexes.toArray()).mapToInt(x -> intArr[(int) x]).toArray();
StringBuilder output = new StringBuilder("");
for(Integer x : bestSequence) {
output.append(x + " ");
}
System.out.println(output.toString().trim());
}
I'm storing indexes instead in preparation for having to access the original array again. Since it's easier to go from indexes to values than vice versa.
Example:
3 6 1 2 8
My code returns: 1 2 8
First sequence is: 3 6 8
Another Example:
1 5 2 3
My code correctly returns: 1 2 3
Basically, my code works as long as the first longest sequence is the same as the best longest sequence. But when you have a bunch of longest sequences of the same length, it grabs the best one not the first one.
Code is self-explanatory. (Have added comments, let me know if you need something extra).
public class Solution {
public static void main(String[] args) {
int[] arr = {3,6,1,2,8};
System.out.println(solve(arr).toString());
}
private static List<Integer> solve(int[] arr){
int[][] data = new int[arr.length][2];
int max_length = 0;
// first location for previous element index (for backtracing to print list) and second for longest series length for the element
for(int i=0;i<arr.length;++i){
data[i][0] = -1; //none should point to anything at first
data[i][1] = 1;
for(int j=i-1;j>=0;--j){
if(arr[i] > arr[j]){
if(data[i][1] <= data[j][1] + 1){ // <= instead of < because we are aiming for the first longest sequence
data[i][1] = data[j][1] + 1;
data[i][0] = j;
}
}
}
max_length = Math.max(max_length,data[i][1]);
}
List<Integer> ans = new ArrayList<>();
for(int i=0;i<arr.length;++i){
if(data[i][1] == max_length){
int curr = i;
while(curr != -1){
ans.add(arr[curr]);
curr = data[curr][0];
}
break;
}
}
Collections.reverse(ans);// since there were added in reverse order in the above while loop
return ans;
}
}
Output:
[3, 6, 8]
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have made a program (for teaching myself purposes) with threads, which is calculating multiplication of elements of an array , using 2 threads. But I get for both threads an ArrayIndexOutOfBoundsException. The error looks like this:
Exception in thread "Thread-1" Exception in thread "Thread-0" Executing multiplying of last2elements
java.lang.ArrayIndexOutOfBoundsException: 1
at FirstPart.run(FirstPart.java:12)
java.lang.ArrayIndexOutOfBoundsException: 1
at SecondPart.run(SecondPart.java:10)
Java Code :
FirstPart.java
public class FirstPart extends Thread {
int multiply = 1;
static int n;
static int[] v = new int[n];
public void run() {
System.out.println("Executing multiplying of first "+MultiplyDemo.cap1+"elements");
for(int i = 1; i <= MultiplyDemo.cap1; i++) {
multiply = multiply * FirstPart.v[i];
System.out.println("Multiplication is "+ multiply);
}
}
}
SecondPart.java:
public class SecondPart extends Thread {
int multiply = 1;
public void run() {
System.out.println("Executing multiplying of last " + (FirstPart.n - MultiplyDemo.cap1) + "elements");
for(int i = MultiplyDemo.cap1;i <= FirstPart.n; i++) {
multiply=multiply*FirstPart.v[i];
System.out.println("Multiplication is "+multiply);
}
}
}
MultiplyDemo.java:
import java.util.Scanner;
import java.util.Vector;
public class MultiplyDemo {
public static int cap1;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("introduceti numarul de elemente din vector:");
FirstPart.n=s.nextInt();
int []v=new int[FirstPart.n];
System.out.println("Elementele vectorului sunt");
for(int i = 0; i < v.length; i++)
v[i]=s.nextInt();
cap1=FirstPart.n / 2;
FirstPart thread1=new FirstPart();
SecondPart thread2=new SecondPart();
thread1.start();
thread2.start();
try { // wait for completion of all thread and then sum
thread1.join();
thread2.join(); //wait for completion of MathCos object
double z = thread1.multiply + thread2.multiply;
System.out.println("produsul elementelor este" +z);
}
catch(InterruptedException IntExp) {
}
}
}
Arrays indexes are 0-based; if an array has a size of n valid indexes are in range 0..n-1.
All your for loops check with a <= instead of using < and this is why you are getting ArrayIndexOutOfBoundsException.
Usually a "for loop" on arrays has this form:
Object[] array = new Object[size];
for(int i = 0;i < array.length;i++) {
..
}
In this way you can never exceed the size of array
Make your both for loop to this :
for(int i=0; i < MultiplyDemo.cap1; i++)
And PS : Please post question in proper format so that it will be easy for someone to help with.
MultiplyDemo.cap1 is bigger than you n leading to your for loop trying to access an index that does not exist:
for(int i=1;i<=MultiplyDemo.cap1;i++)
multiply=multiply*FirstPart.v[i]; // Misses index 0 and tries to go to index n, when n-1 is max
FirstPart.v is still an empty array. You are assigning the value to n from the main() method and initializing values to a local array which doesn't affect FirstPart.v
Your "n" defaults as 0, and so your v array has 0 length.
This is why you're getting index out of bounds.
In your main method, you're initalizing a new "v" variable. Keep in mind that this "v" array is not the same static "v" array as in "FirstPart"