似乎无法将文件读入矩阵?

时间:2016-03-10 01:50:21

标签: java matrix

public void getMatrix() throws FileNotFoundException{

File file = new File("C:/Users/Cameron/Desktop/words.txt");
String largest =" ";
int col = 0;
int count=0;

    Scanner sc = new Scanner(file);
    Scanner newsc = new Scanner(file);

    while (sc.hasNextLine()) {
        String i = sc.nextLine();
        count++;

         if(i.length()>largest.length()){
            largest=i;
            col = largest.length();

        }

    }

  int rows = (int)(Math.random()*count +1);  

  String data[][] = new String[rows][col];

  while(newsc.hasNextLine()){
    String c = newsc.nextLine();

    for(int i=0; i<rows; i++){
        for(int j=0; j<col; j++ ){

        data[i][j] = c;

    }
    }
  }

    for(int r=0; r<data.length; r++)
    {
        for(int c=0; c<data[0].length; c++)
        {
            System.out.print(data[r][c]+" ");
        }
        System.out.println();  //Moves to next line
    }

}

我正在尝试从文件中读取单词(现在,我需要稍后制作它们)但是我在将单词读入矩阵时遇到了麻烦。假设矩阵具有随机大小,但是它应该考虑将要读入的设定范围内的最长单词。我得到了矩阵列中最长单词的长度然后根据文件中的单词数得到行的随机数。每当我打印矩阵时,它在整个事物中只打印一个单词。我知道这是因为while循环和double for循环组合只占用了文件的第一个单词,但我似乎找不到解决方法。

这是我想要看到的(在某种程度上):

ladybug hamburger lettuce computer compiler java cologne
book encyclopedia dictionary guitar euphonium nutcracker
mouthpiece outlet calculus lightsaber

这是我实际看到的(再次,在某种程度上):

lightsaber lightsaber lightsaber lightsaber lightsaber lightsaber
lightsaber lightsaber lightsaber lightsaber lightsaber lightsaber
lightsaber lightsaber lightsaber lightsaber lightsaber lightsaber
lightsaber lightsaber lightsaber lightsaber lightsaber lightsaber

1 个答案:

答案 0 :(得分:0)

在此代码中

while(newsc.hasNextLine()){
    String c = newsc.nextLine();

    for(int i=0; i<rows; i++){
        for(int j=0; j<col; j++ ){

        data[i][j] = c;

    }
    }
  }

您正在使用data

替换c的每个值

    for(int i=0; i<rows; i++){

      for(int j=0; j<col; j++ ){

        if (newsc.hasNextLine()){
           String c = newsc.nextLine();
           data[i][j] = c;
        }

      }
    }

最后一个循环也应该是

for(int r=0; r<data.length; r++)
{
    for(int c=0; c<data[r].length; c++)
    {
        System.out.print(data[r][c]+" ");
    }
    System.out.println();  //Moves to next line
}
相关问题