程序循环无限

时间:2014-04-06 05:35:31

标签: java

我编写的程序从用户那里获取命令并执行特定功能。但是,对文件的功能读写输入有问题导致循环无限期运行。

 import java.util.HashMap;
 import java.util.Scanner;


 public class cShell{

    static String Currentpath="C:\\";
    public String Current = Currentpath;

    static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();

    public static void main(String[] args)
    {


    myhashData.put("ltf", new cITF());
    myhashData.put("nbc", new cNBC());
    myhashData.put("gdb", new cGDB());
    myhashData.put("Tedit", new cTedit());

    do
    {


            System.out.print(Currentpath+"> ");

            String Input = null;
            Scanner scan = new Scanner(System.in);
            if(scan.hasNext()){
                Input = scan.nextLine().trim();

            }

            //if(Input.equals("exit")){
            //  System.exit(0);
            //}

            if(myhashData.containsKey(Input))
            {
                ICommand myCommand=myhashData.get(Input);
                myCommand.Execute();
            }
            else
            {
                System.out.println("Invalid Command");
            }


    }while(!"Input".equals("exit"));
  }
}

这是提供读写功能的类。

 import java.util.*;
 import java.io.*;
 //import java.lang.System.*;

 public class cTedit implements ICommand{

     @Override
     public void Execute() {
    // TODO Auto-generated method stub


         System.out.println("Enter the file name to be edited");
         Scanner scan = new Scanner(System.in);
         String filename = scan.nextLine();

                 InputStreamReader cin = null;
         FileWriter out = null;

    try{
        cin = new InputStreamReader(System.in);
        out = new FileWriter(cShell.Currentpath+"\\"+filename);
        System.out.println("Enter character, 'q' to quit");
        char c;

        do{
            c = (char) cin.read();
            out.write(c);
        }while(c!= 'q');
    }
    catch(Exception e){
        System.out.println("Error");
    }
    finally{

            try{
            cin.close();
            out.close();
        }
        catch(IOException e)
        {
            System.out.println("File did not close");
        }
             }
       }
  }

问题在于,在读写之后,程序输出消息&#34; Invalid Command&#34;这是在类cShell中定义的。任何人都可以指出我这是什么原因.. ??

2 个答案:

答案 0 :(得分:3)

do-while循环将永久运行,因为它的终止条件是:

!"Input".equals("exit")

字符串 "Input" 永远不会等于字符串"exit"。您可能希望改为使用变量Input

!input.equals("exit")

注意:

  • 尝试遵循Java命名约定。对方法/变量使用'mixedCase',对类/接口使用'CamelCase'。换句话说,变量名称应为input,而不是Input

答案 1 :(得分:2)

更改

while(!"Input".equals("exit"));

while(!Input.equals("exit"));

由于"Input"永远不能等于"exit",因此条件始终为真,因此它无限循环。

对于NPE,您可以添加空检查

finally{

        try{
        if(cin != null)
           cin.close();
        if(out != null)
           out.close();
    }
    catch(IOException e)
    {
        System.out.println("File did not close");
    }
   }
相关问题