【发布时间】:2016-01-28 14:18:09
【问题描述】:
我不知道把我的 ELSE 语句放在哪里,如果我把它放在 for 循环中,在 IF 语句之后,它会重复 else 语句中的内容很多次。但是,如果我在 ELSE 语句中输入我想要输出的内容,例如在 FOR 循环之外“抱歉找不到此车牌”,那么它会在我不想要的时候输出。
else // or
{
// this code reads a file in
String full="";
try { FileReader reader = new FileReader("address.txt"); // new file reader to read in a file called address
BufferedReader OwnerDetails = new BufferedReader(reader); // reads in the file efficiently
String line; // assigning a string
while ((line = OwnerDetails.readLine()) != null) { // reads in all file
full=full+line;
}
reader.close(); // the reader close, it finishes reading it in
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(full); // reads in whole file, and outputs it, used to check if the file had been written in
// it is commented out once program is finished, but is used when testing
String[] details = full.split(","); // splits up info into arrays
String searchword=registration; // searchword is set as the registration plate entered
for (int i=0;i<details.length-2;i=i+1)
{
if(searchword.equals(details[i])) // if the search word is in the file
{
System.out.println("Name: " +details[i-1]); // outputs name
System.out.println("Registration: "+details[i]); // outputs reg plate again
System.out.println("Address Line 1: "+details[i+1]); // outputs address
System.out.println("Address Line 2: "+details[i+2]); // outputs address line 2
fw2.write(details[i-1]+","); // separates the details when writing in to the file
fw2.write(details[i]+",");
fw2.write(details[i+1]+",");
fw2.write(details[i+2]+",");
fw2.write(speed+"/n");
fw2.close(); // file writer closes
}
}
System.out.println("The numberplate entered could not be found in the file, sorry."); // outputted if registration is not found
}
任务是在文件中搜索车牌,如果不在文件中,则输出不在文件中。
上面代码的输出是:
the speed the car was driving at was: 39.47 mph Name: Adam Davies Registration: AA12ASD Address Line 1: 1 New Road Address Line 2: Northfleet The numberplate entered could not be found in the file, sorry.
【问题讨论】:
-
@Rakesh - 我还是不明白,我读了另一个问题,他们说把 else 语句放在 for 循环之外,但这让它每次都输出,我需要一个布尔值吗?跨度>
-
很难理解你的应用程序需要做什么,因为这里没有人知道上下文。我不确定你说
using the else outside the for loop是什么意思。没有if,else条件永远不会存在,并且它必须始终在if语句之后。否则,它将无法编译。当您将 else 放在“for循环之外”时,我什至不知道您的代码是如何编译的。也许有一个预先存在的if条件而没有其他条件?。 -
你想看我的代码吗?我真的需要帮助,我不知道我做错了什么
-
关键是你的问题没有真正的意义。请参阅此链接,了解如何提出最小、完整和可验证的问题:*.com/help/mcve
标签: java eclipse if-statement task eclipse-kepler