I am building an interface that executes an action depending on the user's input. If the user inputs '1', the program will send the sensor data by MQTT, if the user inputs '2', the sensor is sent by CoAP. Below is my code:
import java.util.Scanner;
import org.eclipse.paho.client.mqttv3.MqttException;
public class MainProgram {
public static void main(String[] args) throws MqttException {
System.out.println("Choose the communication protocol");
System.out.println("1. MQTT");
System.out.println("2. CoAP");
try(Scanner scanner = new Scanner(System.in)){
if(scanner.nextLine().equals("1")){
try {
new UltrasonicSensorMQTT().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if(scanner.nextLine().equals("2")){
try {
new UltrasonicSensorCoAP().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
System.out.println("Invalid input. Client destroyed !");
}catch(Exception e){
e.printStackTrace();
}
}
}
However, the problem is that, the program can only work if I input '1', then it will execute the class UltrasonicSensorMQTT. If I input '2' and any other letter, nothing happens, the class UltrasonicSensorCoAP doesn't run (this class runs perfectly fine in a standalone version), but when I press ENTER again, the line "Invalid input. Client destroyed !" is printed. Does anyone has an idea how to fix this and make it work as I intended
nextLine()you are moving to next line. You need to store its result and compare that stored value in your if statements, not directly callingnextLine(). (now where is that duplicate).