0

I am having trouble displaying an array by index, I don't know why this is happening. Any help will be greatly appreciated. Here is a snippet of my code:

// create token2
    String token2 = "";

    // create Scanner inFile2
    Scanner inFile2 = new Scanner(new File
    ("/Users/timothylee/KeyWestHumid.txt")).
            useDelimiter(",\\s*");

    // create temps2
    List<String> temps2 = new LinkedList<String>();

    // while loop
    while(inFile2.hasNext()){

        // find next
        token2 = inFile2.next();

        // initialize temps2
        temps2.add(token2);
    }

    // close inFile2
    inFile2.close();

    // create array
    String[] tempsArray2 = temps2.toArray(new String[0]);

    // for-each loop
    for(String ss : tempsArray2){

        // display ss
        System.out.println(tempsArray2[0]);
    }
4
  • 1
    I am having trouble displaying an array by index, I don't know why this is happening. What's the trouble, what's the display, and what is happening? Commented Nov 8, 2013 at 2:38
  • What are you trying to accomplish here? Your code simply makes no sense. Commented Nov 8, 2013 at 2:39
  • 2
    improve the last line: System.out.println(ss); Commented Nov 8, 2013 at 2:40
  • Here is an answer that may be useful in helping you traverse your linked list: stackoverflow.com/a/10167545/772020 Commented Nov 8, 2013 at 2:42

3 Answers 3

1
// for-each loop
for(String ss : tempsArray2){

    // display ss
    System.out.println(tempsArray2[0]);

your problem is here. you're not actually using the ss variable at all, you're simply displaying the first string each time around the loop.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2967353, if you're tyring to use an enhanced for loop, you should learn how to use it correctly.
1

improve your for loop:

// for-each loop
for(int i=0;i<tempsArray2.length;i++){
    // display ss
    System.out.println(tempsArray2[i]);
}

If you prefer for-each:

// for-each loop
for(String ss : tempsArray2){

    // display ss
    System.out.println(ss);
}

1 Comment

I would suggest the first way, since OP seems to not know how to use enhanced for loops.
0

You have put in your enhanced for loop correctly, its only the items you are not picking properly. Using enhanced for loop loop allows you to pick items without using indexes.

Change your loop from

// for-each loop
    for(String ss : tempsArray2){

        // display ss
        System.out.println(tempsArray2[0]);
    }

to

// for-each loop
    for(String ss : tempsArray2){

        // display ss
        System.out.println(ss);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.