这是这个问题的后续:Assigning 1 line of a txt file to a string via scanner 我已经实现了 ArrayList,这样如果提供了答案,程序应该 hibernate 10,000 毫秒(否则它会要求您“查找”(注意 a.txt 的格式是
- 问题
- 回答
- 问题
- 回答)
但是,当我运行该程序时,即使提供了答案,它仍然会要求您“查找”而不是 sleep ,我很确定这与我如何找到问题/答案有关。这是我的代码,Eclipse 显示没有错误 -
public class Test {
public static void main(String[] args) throws InterruptedException {
// Location of file to read
File file = new File("a.txt");
List<String> lines = new ArrayList<String>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
scanner.close();
for (int i = 1 ; i < lines.size(); i+=2)
{
String question = lines.get(i - 1);
String answer = lines.get(i += 1);
String a = JOptionPane.showInputDialog("" + question);
if (a==answer){
Thread.sleep(10000);
}else
JOptionPane.showMessageDialog(null,"Please look it up");
}
} catch (FileNotFoundException e) {
System.out.println("Can't find file");
}
}
}
感谢您的帮助。 编辑:我的代码现在看起来像这样,但仍然无法运行 - http://pastebin.com/C16JZGqH
最佳答案
比较字符串时使用.equals
if (a==answer){
应该是
if (a.equals(answer)){
编辑: 乍一看,字符串比较似乎是问题所在,但是正如斯科特在他的回答中提到的那样,这不是您唯一的问题。您正在循环内自动递增 for 循环控制变量,这是发生困惑的线索。
像这样修改循环,从 0 开始控制变量,并记下对 lines.get
调用的更改
for (int i = 0 ; i < lines.size(); i+=2)
{
String question = lines.get(i);
String answer = lines.get(i+1);
String a = JOptionPane.showInputDialog("" + question);
if (a.equals(answer){
Thread.sleep(10000);
}else
JOptionPane.showMessageDialog(null,"Please look it up");
}
关于java - 数组未定位右行 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135403/