从文件中读取字符串

时间:2015-04-25 01:00:50

标签: java

通过读取String,我在代码中做错了什么。 假设以下String作为layout传递:

String m = "..z\n"+
          "...\n"+
          "...\n"+
          "...\n"+
          "z..\n"+
          "";

我的方法应该返回相同的结果,但它不会返回任何东西,它不会引发任何事情。请不要建议使用StringBuilder或类似的smth。请问smb请帮我解决这个问题?

public static Shape makeShape(String layout,char displayChar)
  {
      Shape result;
      int height = 0;
      int width = 0;
      Scanner data = new Scanner(layout);
      char[][] temp;
      while(data.hasNextLine())
      {
          String line = data.nextLine();
          height = line.length();
          width++;
      }
      temp = new char[height][width];

      Scanner data2 = new Scanner(layout);
      while(data.hasNextLine())
      {
          String line2 = data.nextLine();
          if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
              throw new FitItException("Empty borders!");

            else {

                for (int r = 0; r < height; r++)
                    for (int c = 0; c < width; c++) {
                        //System.out.println(line2.charAt(c));

                        if (temp[r][c] == '.') {
                            temp[r][c] = displayChar;
                        }
                        System.out.println(line2.charAt(temp[r][c]));

                    }
            }
      }
      result = new CreateShape(height, width, displayChar);
      return result;
  }

2 个答案:

答案 0 :(得分:1)

提示:在这两行中仔细

  Scanner data2 = new Scanner(layout);
  while(data.hasNextLine())

你看到......变量......名字......出错了吗?

答案 1 :(得分:0)

鉴于上面的代码和字符串宽度为5或6.没有行超过3,所以line2.charAt(width)会抛出异常?