Icy*_*100 0 java arrays arraylist
这是这个问题的后续问题:通过扫描仪将1行txt文件分配给字符串 我已经实现了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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.编辑:我的代码现在看起来像这样,但仍然没有运行 - http://pastebin.com/C16JZGqH
比较字符串时使用 .equals
if (a==answer){
Run Code Online (Sandbox Code Playgroud)
应该
if (a.equals(answer)){
Run Code Online (Sandbox Code Playgroud)
编辑:乍一看,看起来字符串比较是问题,但斯科特在他的回答中提到它不是你唯一的问题.您在循环内自动递增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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |