如果条件为真,则停止代码

时间:2014-10-14 20:16:04

标签: java

问题出在while循环中,有一条评论

BufferedReader user = new BufferedReader(new FileReader(
        "C:\\Users\\Ionut\\workspace\\tBot\\persoane.txt"));

String line;
while ((line = user.readLine()) != null) {
    if (line.toLowerCase().contains(nume.toLowerCase())) {
        System.out.println("Ce mai faci " + nume + "?");
        ceva = scanIn.nextLine(); //here i want to stop if the condition is true, but it will show the message and go ahead and execute the rest of the code
    }
}

1 个答案:

答案 0 :(得分:2)

基本上有两种常见的解决方案:

1-使用break

while ((line = user.readLine()) != null) {
    if (line.toLowerCase().contains(nume.toLowerCase())) {
        System.out.println("Ce mai faci " + nume + "?");
        ceva = scanIn.nextLine(); 
        break;  // exists the closest loop
    }
}

2-使用boolean标志:

boolean stop = false;
while (!stop && (line = user.readLine()) != null) {
    if (line.toLowerCase().contains(nume.toLowerCase())) {
        System.out.println("Ce mai faci " + nume + "?");
        ceva = scanIn.nextLine();
        stop = true;
    }
}