yonuthim
yonuthim

Reputation: 1

stop code if the condition is true

the problem is at the while loop, there is a comment

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
    }
}

Upvotes: 0

Views: 110

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53819

Basically two common solutions:

1- Using 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- Using a boolean flag:

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;
    }
}

Upvotes: 2

Related Questions