【问题标题】:my java program is not working after I execute file io执行文件 io 后我的 java 程序不工作
【发布时间】:2018-08-10 09:28:34
【问题描述】:

你好,我有一个任务,我的代码不工作。我要求用户输入文件名,然后它冻结并且不处理行数。我做错了什么,但我不确定是什么?有人可以帮我吗,我真的很绝望,这部分正在使我的整个程序崩溃,我可能会失败,我不知道该问谁:(寻求帮助

    public static void fileReader()
{
  Scanner sc = new Scanner(System.in); 

  int catNum; 
  int dogNum; 
  int fishNum; 
  String fileName;

  System.out.println("Please enter the Name of the file you want to read in 
  from"); 
  fileName = sc.nextLine(); 
  System.out.println("this is the file name --> "+fileName);

  catNum = TestFile.getNum(fileName, "cat"); 
  dogNum = TestFile.getNum(fileName, "dog"); 
  fishNum = TestFile.getNum(fileName, "fish"); 

  System.out.println("THE CAT IS" +catNum); 
  System.out.println("THE DOG IS" +dogNum); 
  System.out.println("THE FISH IS" +fishNum);

}

在我询问它冻结的文件名后,我没有发现任何错误

public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;


FileInputStream fileStrm = null;
InputStreamReader rdr; 
BufferedReader bufRdr;
String line;

try {

     fileStrm = new FileInputStream (fileName);
     rdr = new InputStreamReader (fileStrm);
     bufRdr = new BufferedReader (rdr);
     line = bufRdr.readLine();

     while (line != null)

     {     
        String firstWord = processString(line);

        if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object 
        {
           lineNum++;   
           line = bufRdr.readLine() ;
        }
     }

     fileStrm.close();
} 
catch (IOException e)
{
  if (fileStrm != null)
  {
      try
         {
           fileStrm.close(); 
         }
      catch(IOException ex2)
         {
         System.out.println("This is Error");    
         }
  }
  System.out.println("error reading file !!" +e.getMessage());
}   
return lineNum; }

文件看起来像这样(每一行都是这样的): CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016

【问题讨论】:

  • 这个问题太笼统了,到底哪里出错了?尝试调试并指定错误。
  • 在我询问它冻结的文件名后直接发生错误我添加了额外的代码只是为了帮助带来一些上下文@ArthurWietzorek

标签: java variable-assignment


【解决方案1】:

看看这个while循环:

 while (line != null)
 {     
    String firstWord = processString(line);

    if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object 
    {
       lineNum++;   
       line = bufRdr.readLine() ;
    }
 }

如果firstWord.equalsIgnoreCase(word) 返回 false,那么会发生什么? line 的值永远不会更新,循环也永远不会退出。

【讨论】:

    猜你喜欢
    • 2012-07-16
    • 1970-01-01
    • 2012-08-13
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多