0

Java method bot

Hello colleagues! Please help me figure out what I’m doing wrong. I cannot complete the task if the value 1 is entered. Here is my code: import java.util.Scanner; public class Program { static void bot() {Scanner sc = new Scanner(System.in); String num = sc.nextLine(); if (num.equals("1")) {System.out.println("Order confirmed");} if (num.equals("2")) {System.out.println("info@sololearn.com");} else {System.out.println("Try again");} } public static void main(String[] args) { bot(); } }

7th Aug 2024, 11:03 AM
Alex Nick
Alex Nick - avatar
2 ответов
+ 1
Alex Nick there is a logic error in the code. Both if statements always get executed. So when the first if statement is true, the second one is false and execution continues into the else clause of the second if statement. After the first one is found to be true, it should stop checking for other options. In other words, it should check the second option only when the first if statement is false.
7th Aug 2024, 11:43 AM
Brian
Brian - avatar
0
Brian thank you so much for you help!👍🙏
8th Aug 2024, 12:47 PM
Alex Nick
Alex Nick - avatar