从文件中读取数据,并将其存储到数组中以输出列表

时间:2021-10-02 15:44:23

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:

我在这里要做的是获取data / txt文件中的内容并将其存储到数组中。现在我只是想做String,但最终我想把文件中的所有东西都输出来。这是txt文件中的内容:

Honduras 130 Tegucigalpa Cuba 100 Habanna

洪都拉斯130 Tegucigalpa Cuba 100 Habanna

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

我希望输出在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++;
      }
    }
}

2 个解决方案

#1


1  

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

你总是在写名字[0],因为你每次循环时都会声明:

int i = 0;

So your i++ is pretty much useless.

所以你的i ++几乎没用。

#2


0  

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

只需将循环外部的变量i定义为将其设置为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++;
      }
    }
}

#1


1  

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

你总是在写名字[0],因为你每次循环时都会声明:

int i = 0;

So your i++ is pretty much useless.

所以你的i ++几乎没用。

#2


0  

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

只需将循环外部的变量i定义为将其设置为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++;
      }
    }
}