java - If statement doesn't trigger while using Scanner -


this question has answer here:

i building interface executes action depending on user's input. if user inputs '1', program send sensor data mqtt, if user inputs '2', sensor sent coap. below 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 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, problem that, program can work if input '1', execute class ultrasonicsensormqtt. if input '2' , other letter, nothing happens, class ultrasonicsensorcoap doesn't run (this class runs fine in standalone version), when press enter again, line "invalid input. client destroyed !" printed. has idea how fix , make work intended

your current code requires input "2" twice trigger second if. after input first time, code sitting on second if condition's call scanner.nextline() , awaiting input.

but when press enter again, line "invalid input. client destroyed !" printed.

because didn't input second time.

don't scan input twice. scan once , store result in variable. perform logic on variable:

string inputvalue = scanner.nextline(); if(inputvalue.equals("1")) {   // ... } else if(inputvalue.equals("2")) {   // ... } // etc. 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -