Fanta
Fanta

Reputation: 11

Make Array From Temporary Arrays

I have a file in where rows of random integers are divided by "::".

For example "1 2 3::4 5:: 6 7 8 9::10 11 12::13"

What I want to make is an array where the rows are combined as follows: take the second row and place at the back of the first row, then take the third row place it in front of the first row, take the fourth row and place it at the back etc.

At the moment I can fill a temporary array with one row and place it in the totalArray but this will get overwritten by with the next row. I can not use ArrayList or multi dimensional arrays.

The code to make it more clear:

class1() {
    in = new Scanner(System.in);
    out = new PrintStream(System.out);

}
public void lineToArray (Scanner intScanner) {
    int i = 0;
    int[] tempArray = new int[100];

    while (intScanner.hasNext()) {
        tempArray[i] = intScanner.nextInt();
        i++;
    }
}
public void readFile() {
    while (in.hasNext()) {
        in.useDelimiter("::");
        String line = in.next();

        Scanner lineScanner = new Scanner(line);
        lineToArray(lineScanner);
    }
}
void start() {
    readFile();
}

and

public class Class2 {
     int[] totalArray = new int[1000];

Class2() {
}

public void addToFront(int[] tempArray, int i) {
    //totalArray = tempArray + totalArray
}   
public void addToBack(int[] tempArray, int i) {
    //totalArray = totalArray + tempArray
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

}

}

Bear in mind that I'm a beginner

Upvotes: 1

Views: 62

Answers (1)

Nikhil Pathania
Nikhil Pathania

Reputation: 821

public static void main(String args[]) throws IOException
{
    Scanner in = new Scanner(System.in);
    PrintWriter w = new PrintWriter(System.out);
    String inp = in.nextLine();
    String s[] = inp.split("::");
    StringBuilder ans = new StringBuilder();
    for(int i = 0; i < s.length; i++){
        if(i == 0){
            ans.append(s[i]);
        }
        else if(i%2 == 0){
            ans.append("::"+s[i]);
        } else{
            ans.reverse();
            StringBuilder add = new StringBuilder(s[i]);
            add.reverse();
            ans.append("::"+add);
            ans.reverse();
        }
    }
    w.println(ans);
    w.close();
}

Output:
1 2 3::4 5:: 6 7 8 9::10 11 12::13
10 11 12::4 5::1 2 3:: 6 7 8 9::13

Upvotes: 1

Related Questions