java - 数组未定位右行 [Java]

标签 java arrays arraylist

这是这个问题的后续: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/

相关文章:

c++ - cv::Mat 初始化使用数组

c - 如何从 C 数组中删除重复的字符串?

java - ArrayList<Class> 中的 String[]

Java 数组列表错误?

android - 为什么Activity重启后ArrayAdapter无法更新listview?

java - Apache CXF 客户端 soap 故障处理

java - 为什么 ForkJoinPool.commonPool().execute(runnable) 需要更多时间来运行线程

java - 包 javax.servlet.jsp 错误

Java Swing : do I need two threads?

python - 编辑数组中的所有其他项目