这是此问题的后续内容:Assigning 1 line of a txt file to a string via scanner 我已经实现了ArrayList,所以如果提供答案,程序应该睡眠10,000毫秒(否则它会要求你“查找”(注意a.txt的格式是
然而,当我运行程序时,即使提供了答案,它仍然会要求你“查找”而不是睡觉,我很确定这与如何定位问题/答案有关。继承我的代码,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
答案 0 :(得分:6)
比较字符串时使用.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");
}
答案 1 :(得分:4)
危险!危险!
String answer = lines.get(i += 1);
在函数调用和循环控制变量内自动递增 - 这可能不太好。
答案 2 :(得分:0)
使用equals()
方法比较两个字符串,而不是==
答案 3 :(得分:0)
for (int i = 1 ; i < lines.size(); i+=2)
{
String question = lines.get(i - 1);
String answer = lines.get(i);
String a = JOptionPane.showInputDialog("" + question);
if (a==answer){
Thread.sleep(10000);
}else
JOptionPane.showMessageDialog(null,"Please look it up");
}
答案 4 :(得分:0)
你说它仍然没有用,但确实如此。 再试一次:
import java.io.*;
import java.util.*;
import javax.swing.*;
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 = 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(1000);
} else
JOptionPane.showMessageDialog(null,"Please look it up");
}
} catch (FileNotFoundException e) {
System.out.println("Can't find file");
}
}
}