user2967353
user2967353

Reputation: 267

Java displaying array one by one by using indexes

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]);
    }

Upvotes: 0

Views: 295

Answers (3)

Juned Ahsan
Juned Ahsan

Reputation: 68715

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);
    }

Upvotes: 0

shawnzhu
shawnzhu

Reputation: 7585

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);
}

Upvotes: 1

panini
panini

Reputation: 2026

// 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.

Upvotes: 1

Related Questions