【问题标题】:Commands from file来自文件的命令
【发布时间】:2014-03-13 02:19:47
【问题描述】:

我正在尝试读取文件并根据文件的每一行所说的内容执行命令。 该文件如下所示:

Add saw cutting tool
Add yen a monetary unit
Add pan a dish
List     


public void Load(String fileName) throws FileNotFoundException{
    BufferedReader r = new BufferedReader (new FileReader(fileName));
    Scanner sc = new Scanner(r);
    while(sc.hasNextLine()){
        while(sc.hasNext()){
            String temp =sc.nextLine();

            **if(temp.startsWith("Add")){
                String word = sc.next().toLowerCase();
                String def = sc.nextLine().toLowerCase();
                Add(word, def);**           

            }else if(temp.equals("List")){
                List();
            }
        }
    }
}

正在打印:

Add saw cutting tool Add yen a monetary unit Add pan a dish

我希望它像这样打印出来:

saw cutting tool
yen a monetary unit
pan a dish

我知道问题不在印刷品上。问题出在**上面。关于如何解决此问题的任何建议?

【问题讨论】:

  • 您需要找到一种方法从字符串中去除“添加”,如果 sc.next.toLowerCase().equals("add)); 跳过并且单词相等,则可以执行另一个条件到 sc.next。这应该会给你想要的结果。我们还能看到你的打印方法吗?
  • @chrisedwards add() 将单词及其定义发送到二叉搜索树中,list() 按字母顺序打印树。

标签: java file java.util.scanner bufferedreader


【解决方案1】:
Do this way: It might solve your problem:

public void Load(String fileName) throws FileNotFoundException{
        BufferedReader r = new BufferedReader (new FileReader(fileName));
        Scanner sc = new Scanner(r);
        while(sc.hasNextLine()){
            while(sc.hasNext()){
                String temp =sc.nextLine();

                if(temp.startsWith("Add")){
                    temp = temp.replaceAll("Add ", "");
                    String[] word = temp.split("\\s", 2);
                    Add(word[0], word[1]);       

                }else if(temp.equals("List")){
                    System.out.println("List");
                }
            }
        }
    }

【讨论】:

    【解决方案2】:

    试试这个

    if(temp.startsWith("Add")){
        String word = sc.next().toLowerCase().replaceFirst("All", "");
        String def = sc.nextLine().toLowerCase().replaceFirst("All", "");;
        Add(word, def);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多