大家早上好,我是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;
}
}
我在您的代码中看到一些错误,这些错误加起来可能会导致根本无法正常工作。他们在这里:
-
变量
word
永远不会更新为以下标记(它最初设置为text[0]
,然后从未更改)。num
也是如此。 -
所有操作都作用于变量
num
和result
,然后将结果放入result1
。因此,中间结果不会从一个操作传递到下一个操作。 -
"输入"操作从
inputField
加载电流值,而无需等待用户实际键入内容。 -
主循环迭代,直到
count
达到程序中的字符数;它应该循环获取令牌数。
此外,以下是一些使您的代码更符合条件的建议:
-
如果你从Java开始,那么去掉Scanner对象,只保留"在空间上拆分"的方法。对于实际问题,我不建议这样做,但正确使用
Scanner
有些复杂。 -
将拆分的单词数组包装到 List 集合中,然后从中获取迭代器。在这里:
Iterator<String> words = Arrays.asList(txt.split("[ ]+")).iterator();
然后,将循环编写为:
while (words.hasNext()) {
String command = words.next();
...
}
-
将操作助记符移到函数之外,并将其标记为 final。
-
从每个操作块内部读取操作参数;这是必需的,因为某些操作不接收参数。
好吧,我不会给你代码,因为这是你自己必须做的事情。希望有帮助。祝你好运。