有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用条件语句从JTextArea读取和编译行

大家早上好,我是java编程的初学者。所以,直截了当地说,我正在创建一个可以读取和编译。txt文件,只需点击一个按钮

我已经看完文件了。我的问题是,我的程序没有编译来自第一个JTextArea的文本,并将结果显示给第二个JTextArea

我已经有这个问题四天了,我一直在尝试用我能想到的任何可能的方式修改代码。有人能告诉我我的代码出了什么问题吗?这肯定会对我有很大帮助

非常感谢大家

    @SuppressWarnings("IncompatibleEquals")
private void executeCodeActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String loadi = "Load";
    String add = "Add";
    String subt = "Subt";
    String mult = "Mult";
    String div = "Div";
    String input = "Input";
    String print = "Print";
    int number = 0;

    String txt = textAreaCode.getText();
    String split = " ";
    String [] text = txt.split(split);
    String word = text[0];
    int num = Integer.getInteger(text[1]);
    int result = num;
    int result1 = 0;
    Scanner scan = new Scanner(txt);
    scan.nextLine();

    for (int count=0;count<txt.length();count++ ) {
        if (loadi.equalsIgnoreCase(word)){
            result1 = num + number;
        }
        else if (add.equalsIgnoreCase(word)){
            result1 = num + result;
        }
        else if (subt.equalsIgnoreCase(word)){
            result1 = num - result;
        }
        else if (mult.equalsIgnoreCase(word)){
            result1 = num * result;

        }
        else if (div.equalsIgnoreCase(word)){
            result1 = num / result;

        }
        else if (print.equalsIgnoreCase(word)){
            textAreaOutput.setText(String.valueOf(result1));
        }
        else if (input.equalsIgnoreCase(word)){
            String nmbr = inputField.getText();
            int nmr = Integer.parseInt(nmbr);
            result1 = nmr + number;
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    我看到你的代码中有一些错误,这些错误加起来可能根本不起作用。这是:

    1. 变量word永远不会更新为以下标记(最初设置为text[0],然后再也不会更改)。这同样适用于num

    2. 所有操作都作用于变量numresult,然后将结果放入result1。因此,中间结果不会从一个操作转移到下一个操作

    3. “input”操作从inputField加载当前值,而不等待用户实际键入内容

    4. 主循环迭代,直到count达到程序中的字符数;它应该循环查找令牌的数量

    此外,以下是一些让你的代码更加灵活的建议:

    1. 如果您是从Java开始的,那么就去掉Scanner对象,只保留“空间分割”方法。对于真正的问题,我不建议这样做,但是Scanner要正确使用有点复杂

    2. 将拆分的单词数组包装到列表集合中,然后从中获取迭代器。这是:

      Iterator<String> words = Arrays.asList(txt.split("[ ]+")).iterator();

      然后,将循环写为:

      while (words.hasNext()) { String command = words.next(); ... }

    3. 将操作助记符移到函数之外,并将其标记为final

    4. 从每个操作块中读取操作参数;这是必需的,因为某些操作不接收参数

    好吧,我不会给你代码,因为这确实是你必须自己做的事情。希望有帮助。祝你好运