简体   繁体   中英

java: splitting one array into two separate arrays based on even and odd positions of the array

I'm new to Java and I'm having difficulties I have an assignment that requires me to load a text file with the name of a state followed by its capital onto the program and read the state names into one array and the capital names into another array. The way I tackled this was that I loaded the text file into one array called total and made a count. I wanted to split those with an even position to be in a separate array called capital and those in an odd position to be in an array called states. But I'm not sure how exactly to put that into code. This is what I have so far

Sample of Text File:

Alabama
Montgomery
Alaska
Juneau
Arizona
Phoenix
Arkansas
Little Rock
California
Sacramento
Colorado
Denver
Connecticut
Hartford
Delaware
Dover
Florida
Tallahassee
Georgia
Atlanta
Hawaii
Honolulu

And my code so far

public class StateCapitals 
{

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException 
    {
        File inputfile;
        File outputfile;
        inputfile = new File("capitals.txt"); 
        outputfile = new File ("InOrder.txt");
        String stateandcity;
        int count;
        count = 1;

        PrintWriter pw;
        Scanner kb;
        kb = new Scanner(inputfile);


         String [] total;
         total = new String[100];

         String [] capitals;
         capitals = new String[50];    

         String [] states;
         states = new String [50];

      while (kb.hasNextLine())
        {
        stateandcity = kb.nextLine();
        System.out.println("Count: " +count + "   " + stateandcity);

        total[count-1] = stateandcity;
         count ++;

        } 

      if (count % 2 == 0)  
          states = new String [50];   //where i need help

    }}

The algorithm will be like this:

  • Read everything into total like you have already thought of.
  • Use a for loop to loop from i=0 to i=100 (or however many items there are to be split), incrementing by 2 each time.
  • Assign total[i] to capital[i / 2] .
  • Assign total[i + 1] to states[i / 2] .

It is as simple as that! Try doing it yourself first. If you are having difficulties, just leave a comment!

I would separate them while reading them like this. (Save yourself a loop)

while (kb.hasNextLine())
    {
    state[count] = kb.nextLine();
    capitals[count] = kb.nextLine();
    System.out.println("Count: " +count + "   " +
                        state[count] + "," + 
                        capitals[count]);

    count ++;    
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM