-1

what I'm trying to do here is get what is inside of a data/txt file and store it into an array. Right now I'm just trying to do the String, but ultimately I will like to get everything in the file to output. This is what is inside the txt file:

Honduras 130 Tegucigalpa Cuba 100 Habanna

I will like for the output to be the same in java.

import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;


public class ReadCountries2
{
    public static void main(String [] args)throws Exception
    {
       String fName = "/Users/Edward Lavaire/Downloads/Countries.txt";
       Scanner s = new Scanner(new File(fName));

       String name [] = new String[6];

       while(s.hasNext())
       {
           int i = 0;
           name[i] = s.next();
           System.out.println(name[i]);
           i++;
      }
    }
}
  • 1
    possible duplicate of [Java read file and store text in an array](http://stackoverflow.com/questions/19844649/java-read-file-and-store-text-in-an-array) – Waog Jun 24 '15 at 13:28
  • is there any possible way to do it without ? – edward lavaire Jun 24 '15 at 13:33
  • Probably. But List is by far your best option. It's the java way of storing an arbitrary amount of data. Arrays are fixed size. – Waog Jun 24 '15 at 20:18

2 Answers2

1

You are always writing to name[0] because everytime you loop through your while you declare:

int i = 0;

So your i++ is pretty much useless.

rhaecker
  • 52
  • 5
0

Just put outside the loop the definition of the variable i instead to set him to 0

import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;


public class ReadCountries2
{
    public static void main(String [] args)throws Exception
    {
       String fName = "/Users/Edward Lavaire/Downloads/Countries.txt";
       Scanner s = new Scanner(new File(fName));

       String name [] = new String[6];
       int i = 0;
       while(s.hasNext())
       {

           name[i] = s.next();
           System.out.println(name[i]);
           i++;
      }
    }
}
alifirat
  • 2,899
  • 1
  • 17
  • 33