How to compare an input string with a declared string for some further conditional actions - arduino-uno

I need to take an input in a string and check if it matches a preset string.
I tried to take the input and match it with the declared string namely, the String yes with my input string String cmd.
But even with matching input, it is running the else condition.
Here's my code.
# define LED1 12
String cmd;
String yes=String("YES");
void setup()
{
Serial.begin(9600);
pinMode(LED1, OUTPUT);
}
void loop()
{
while(Serial.available())
{
cmd=Serial.readString();
if(cmd.equals(yes)) //checking equality of my input string with the predefined string.
{
//code to do something with the LED
}
else
{
//some error message
}
}
}

You are missing "\r\n" in your input string. Try this
String yes=String("YES\r\n");
and if possible avoid the String altogether and follow this awesome tutoral

Related

While using FileReader class in java why is it compulsory to store the value of r.read in i first and then type caste it? why can't we typecast r.read

[it is giving wrong output when I use f1.read directly .. why is it compulsory to use (i=f1.read) and then type caste i into the file .. why can't we use f1.read directly..] 1
//why this code is giving wrong output
// why is it compulsory to first store the value of f1.read in i
import static java.lang.System.out;
import java.io.*;
import java.util.*;
public class third{
public static void main(String [] args) {
try{
FileReader f1 = new FileReader("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
FileWriter f2 = new FileWriter("C:\\Users\\Akshita Agarwal\\Desktop\\b.txt");
try{
while(f1.read() !=-1){
f2.write((char)f1.read());
}
}
finally {
f2.close();
}
}
catch(IOException e){
out.println(e);
}
}
}
char is two bytes unsigned. int -1 is outside this range.
Your code does not close f1 and it writes half of the file, every second char.
It could be written as:
for (;;) {
int c = f1.read();
if (c == -1) {
break;
}
f2.write((char)c);
}
You suggestion
for (;;) {
char c = (char) f1.read();
if (c == (char)-1) {
break;
}
f2.write(c);
}
has one drawback.
You could embed a ((char) -1) or '\uFFFF' in the middle of your file, and only
half of the file would be read.
The shortest code is:
for (int c; (c = f1.read()) != -1;) {
f2.write((char)c);
}
However it:
reads and writes per character
there is a conversion reading from binary data using the platform encoding to (Unicode) text
there is a conversion writing from (Unicode) text to binary data using the platform encoding.
Here you could do:
Path path1 = Paths.get("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
Path path2 = Paths.get(System.getProperty("user.home"), "Desktop\\b.txt");
Files.copy(path1, path2);
or read by lines:
Charset charset = Charset.defaultCharset();
try (BufferedWriter writer = Files.newBufferedWriter(path2, charset));
Stream<String> reader = Files.lines(path1, charset)) {
reader.forEach(line -> bw.write(line + "\r\n"));
} // Automatically closes reader and writer.
The charset is needed to use the platform encoding. Per default it uses UTF-8, Unicode for the full range of possible characters for all languages.
Try-with-resources is a weird syntax try (<DECLARATIONS>) { ... } that ensures closing of the (auto-)closeable variables in the declarations. Even on return, break or exception.
The lines read are stripped from line endings CR-LF = "\r\n" (Windows), LF (Unix), CR, NEL (AS/400 e.a.).

How to properly apply this nested ifstream?

I want to use an ifstream function that calls another ifstream function inside it, but I have no idea why it does not work. The ifstream called first works fine, but the second one does not. This is the first one:
ifstream archivo("civilizaciones.txt");
if(archivo.is_open()){
while(!archivo.eof()){
string name;
Civilizacion a;
getline(archivo, name);
if(archivo.eof()){ break; }
a.setName(name);
arreglo.push_back(a);
c.recuperarAld(name);
}
}
c.recuperarAld(name) Calls the following function in a class with object c:
void Civilizacion::recuperarAld(string name)
{
ifstream aldeanoss(name + ".txt");
if(aldeanoss.is_open()){
while(!aldeanoss.eof()){
Aldeano a;
string linea;
getline(aldeanoss,linea);
if(aldeanoss.eof()){break;}
a.setNombre(linea);
getline(aldeanoss, linea);
a.setEdad(stoul(linea));
getline(aldeanoss, linea);
a.setGenero(linea);
getline(aldeanoss, linea);
a.setSalud(stoi(linea));
aldeanos.push_back(a);
}
}
}
But this second one does not seem to work, how can I fix it?

Convert string input of linedit() to int for use as an integer variable

I designed a simple GUI to check Database connectivity. The DB connection parameters such as DB name, Host name, user name, password, port etc will be entered from GUI and the output will be a RED or GREEN image depending upon the connectivity.
I have set up oracle OCI plugin (DB is oracle 10g)
and done the following--
void MainWindow::on_GoButton_clicked()
{
QString HostN = ui->HostNameEdit->text();
QString DatabaseN = ui->DatabaseNameEdit->text();
QString UserN = ui->UserNameEdit->text();
QString PassWD = ui->PasswordEdit->text();
QString PortNO = ui->PortEdit->text();
QSqlDatabase db = QSqlDatabase::addDatabase("QOCI");
db.setHostName(HostN);
db.setDatabaseName(DatabaseN);
db.setUserName(UserN);
db.setPassword(PassWD);
db.setPort(PortNO);
while(true)
{
if (db.open())
{
// do this
}
else
{
//do that
}
}
}
Now it is showing error--
/home/aj/MY_QT_WORK/DB_connection_test/mainwindow.cpp:19: error: no matching function for call to ‘QSqlDatabase::setPort(QString&)’
Any ideas ???
You could write it as:
db.setPort(PortNO.toInt());
However for much correctness you have to be sure that the PortNO string is really convertible to an integer value. Therefore you can use a flag that will indicate the successful conversion:
bool ok;
int portNumber = PortNO.toInt(&ok);
if (!ok) {
qDebug() << "The port number is incorrect";
// return?
}

Hiding the keyboard when a control loses focus?

now I have this:
public void focusChanged(Field field, int eventType) {
if ( field == txtAmount && eventType == 1)
{
getVirtualKeyboard().setVisibility(VirtualKeyboard.HIDE);
}
}
Now my problem is that the keyboard isn't hiding. I think the error is in the eventType parameter. What number identifies a LostFocus event? I hard coded in '1' for tests but it doesnt seem to work.
FocusChangeListener focusListener;
//In the constructor:
txtAmount = new EditField(Field.FIELD_RIGHT);
txtAmount.setFocusListener(focusListener);
public void focusChanged(Field field, int eventType) {
if ( field == txtAmount && eventType == 1)
{
Dialog.alert("iasdi");
getVirtualKeyboard().setVisibility(VirtualKeyboard.HIDE);
}
}
why isn't this working? is there an enum or something that i can use to choose what eventType I should react to?
Also, if I remove the event type (so that the code executed regardless of the action just when focus changes right? nothing happens the dialog I put in for show, doesn't display meaniing the event is never entered. Any suggestions?
thanks
eventType can be one of next constants, declared in FocusChangeListener class:
public static final int FOCUS_GAINED = 1;
public static final int FOCUS_CHANGED = 2;
public static final int FOCUS_LOST = 3;
!!! Use FOCUS_LOST = 3 instead of FOCUS_GAINED = 1 to handle focus lost event.
Also, check for null getVirtualKeyboard() method returning value, because it returns null on touch devices without virtual keyboard (like Bold 9700).
public static void hideVirtualKeyboard() {
if (net.rim.device.api.ui.VirtualKeyboard.isSupported()) {
Screen screen = UiApplication.getUiApplication().getActiveScreen();
if (null != screen) {
net.rim.device.api.ui.VirtualKeyboard vk = screen
.getVirtualKeyboard();
if (vk != null) {
vk.setVisibility(net.rim.device.api.ui.VirtualKeyboard.HIDE);
}
}
}
}
For matching the eventType, try using the constants defined in FocusChangeListener instead of hard coding "1". In this case, you probably want to use FocusChangeListener.FOCUS_LOST.
As for the case of the code not running, are you actually setting the value of the "focusListener" variable? From the code you posted, you aren't and it will just be passing as "null" into setFocusListener().

refactor dilemma

I want to extract the guard statement from the following method
private void CreateProxy()
{
//extract the following guard statement.
Host selected = this.comboBox1.SelectedItem as Host;
if (selected == null)
{
return;
}
this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
}
//extracted guard method
public bool IsHostSelected()
{
Host selected = this.comboBox1.SelectedItem as Host;
if (selected == null)
{
return false;
}
return true;
}
see? now i have to add return value for the extracted method, is this kinda ugly?
any better solution to avoid adding the return value for the extracted method?
I don't see the big deal. First, I would rewrite it as:
static bool SelectedItemIsHost(ComboBox box) {
return box.SelectedItem is Host;
}
Note the rename, the ComboBox as a parameter, and the body change.
Now, this makes your code read more clearly:
void CreateProxy() {
if(SelectedItemIsHost(this.comboBox1)) {
this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
}
}
So now it reads "if the selected item is a Host then do stuff."
Now, this goes way beyond your question, but this looks like a big coupling of UI logic and domain logic. You might want to reconsider a decoupling there.
any better solution to avoid adding the return value for the extracted method?
Yes:
//extracted guard method
public bool IsHostSelected()
{
Host selected = this.comboBox1.SelectedItem as Host;
return selected != null;
}

Resources