How to fix this "if" statement? - if-statement

The problem is that when the answer is null, it should show as "lollie or flavour did not enter", but it is not working.
var lollie;
var flavour;
lollie = prompt("Please enter type of lollie", "");
if (lollie != null) {
document.writeln("<p>lollie);
} else {
document.writeln(lollie = "lollie was not entered");
}
flavour = prompt("Please enter flavour", "");
if (flavour != null) {
document.writeln("<p> flavour <p>");
} else {
document.writeln(flavour = "You did not enter flavour");
}

You need to use && (logical AND) instead of || (logical OR):
var firstname;
var lastname;
var height;
firstname = prompt("Please enter first name of player 1", "");
if (firstname != null && firstname != "") {
document.writeln("<td>" + firstname + "</td>");
} else {
document.writeln(firstname = "First name not supplied");
}
lastname = prompt("Please enter Last name of player 1", "");
if (lastname != null && lastname != "") {
document.writeln("<td>" + lastname + "</td>");
} else {
document.writeln(lastname = "Last name not supplied");
}
height = prompt("Please enter height of player 1", "");
if (height != null && height != "") {
document.writeln("<td>" + height + "</td>");
} else {
document.writeln(height = "Height not supplied");
}
You'll also need to work a bit on your HTML markup, but I guess that is a Work In Progress.

Delete
firstname != ""
Only write this in if statement:
if(firstname !=null)

use && in your condition. and make sure you trim those variables.

Related

How to simplify multiple if else statement using Java

I've use-case where I've to validate two inputs and return success/failed in responses.
Please find my code below, I feel I'm using too many if-else statements - how can we simplify this?
I've to check given string is null or not, then check if matches the pattern - then return success or failure based on below given conditions:
public class Main {
public static void main(String[] args) {
// Scenario 1: -> Return Success
String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
String input2 = "bearer kiIkdqAplMNbeieW3dJKidAkdmElsEpsles";
// Scenario 2: -> Return Success
//String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
//String input2 = null;
// Scenario 3: -> Return Failed
//String input1 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
//String input2 = "bearer ";
// Scenario 4: -> Return Failed
//String input1 = null;
//String input2 = "bearer sDjdESddfEsdfdfwere2sEDaa2SmnsSkeew";
String result = validate(input1, input2);
System.out.println("result: " +result);
}
private static String validate(String input1, String input2) {
Pattern pattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+)=*$", Pattern.CASE_INSENSITIVE);
String status ="failed";
if (input1 != null && input2 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")
&& StringUtils.startsWithIgnoreCase(input2, "bearer")) {
if (!pattern.matcher(input1).matches() || !pattern.matcher(input2).matches()) {
System.out.println("Pattern not match");
// throw exception here
}
status = "success";
}
} else if (input1 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")) {
if (!pattern.matcher(input1).matches()) {
System.out.println("Pattern not match");
// throw exception here
}
status = "success";
}
}
return status;
}
}
You can group the ifs related to the same input
if (input1 != null) {
if (StringUtils.startsWithIgnoreCase(input1, "bearer")) {
// INTO
if (input1 != null && StringUtils.startsWithIgnoreCase(input1, "bearer")) {
And include the tests about input2 inside the if for input1
Final code
private static String validate(String input1, String input2) {
Pattern pattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+)=*$", Pattern.CASE_INSENSITIVE);
String status = "failed";
if (input1 != null && StringUtils.startsWithIgnoreCase(input1, "bearer")) {
if ((input2 != null && StringUtils.startsWithIgnoreCase(input2, "bearer") && !pattern.matcher(input2).matches())
|| !pattern.matcher(input1).matches()) {
System.out.println("Pattern not match");
// throw exception here
} else {
status = "success";
}
}
return status;
}

Trying to print invalid email address from a list using c++?

I am trying to print a list of invalid emailaddress (which has a space and does not have a # or .) from a list of email addresses. The list has a few email addresses which have spaces, and no '#' or '.' but still it does not print anything.
//Declaring boolean variables
bool atPresent;
bool periodPresent;
bool spacePresent;
string emailid = someemailfrom a list;
atPresent = false;
periodPresent = false;
spacePresent = false;
//looking for #
size_t foundAt = emailid.find('#');
if (foundAt != string::npos) {
atPresent = true;
}
//looking for '.'
size_t foundPeriod = emailid.find('.');
if (foundPeriod != string::npos) {
periodPresent = true;
}
//looking for ' '
size_t foundSpace = emailid.find(' ');
if (foundSpace != string::npos) {
spacePresent = true;
}
//checking to see if all conditions match
if ( (atPresent == false) && (periodPresent == false) && (spacePresent == true)) {
cout << emailid << endl;
}
(atPresent == false) && (periodPresent == false) && (spacePresent == true)
Is wrong. It is only true, when all of the three criteria for an invalid adress are met. But an address is invalid as soon as at least on criteria is met. This would be
(atPresent == false) || (periodPresent == false) || (spacePresent == true)
And simplified:
!atPresent || !periodPresent || spacePresent
replace && statements by || statements : you are only printing those which doesn't have # AND have a space AND have a period. You should use a regex, so you can do it on one line, and know how to use them is always usefull when you try to validate user data

This program is automatically exiting after finishing any one action, why?

My program is exiting after giving one command every time and I am unable to find a logical reason why. I have checked all my loops and if-statements for exit codes but was not able to located any.
the program includes many classes and functions, but here is main:
int main()
{
int local_location = 0;
vector<string>Inventory = { "", "", "" };
unordered_set<string> excl = { "in", "on", "the", "with" };
string word;
array<string, 2> command;
size_t n = 0;
command.at(1) = "";
command.at(0) = "";
while (n < command.size() && cin >> word) {
auto search = excl.find(word);
if (search == excl.end())
command.at(n++) = word;
}
if (command.at(0) == "look") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "get") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "drop") {
look(command.at(1), local_location, Inventory);
}
else if (command.at(0) == "bag") {
bag(Inventory);
}
else if (command.at(0) == "go") {
look(command.at(1), local_location, Inventory);
}
}
Loop over standard input and reset the condition on n after processing the command.
while(cin>>word)
{
auto search = excl.find(word);
if (search == excl.end())
command.at(n++) = word;
if (n== command.size())
{
// process the command
// reset n=0
}
}

It's checking only firs row in table. help someone :) C# winForm

SqlConnection con = new SqlConnection(#"Data Source=(local)\SQLEXPRESS; Integrated Security= SSPI;" + "Initial Catalog = CarRent_vaxo;");
con.Open();
string strSQL = "select * from AccesList";
SqlCommand myCommand = new SqlCommand(strSQL, con);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
myDataReader.Read();
{
if (usertextBox.Text == myDataReader["User"].ToString() && paswordTextBox.Text == myDataReader["Password"].ToString())
{
this.Hide();
ResultForm rf = new ResultForm();
rf.Show();
}
else if (usertextBox.Text == "" || paswordTextBox.Text == "")
{
Notificarion2.Text = "PLEASE FILL THE BOXES !!!";
}
else
{
Notificarion2.Text = "WRONG USER OR PASSWORD !!!";
usertextBox.Text = "";
paswordTextBox.Text = "";
}
}
}
You should read from SqlDataReader in a while loop as
while (myDataReader.Read())
{
//your code goes here
}
myDataReader.Close();
http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx

Webmatrix - including int's in my search page

i have built a fully working search page for my WebMatrix property site. To summarize, it checks the query string, and if any of the defined values are present, it adds it to a list so it can iterate through them.
The problem, as you will see, if that it currently adds everything to the list as a string. This causes problems when i need to use the value as an INT (PropertyType and NumBedrooms should be int's). is there a way i can use both strings and int's in this scenario? can i add ints AND strings to the same list?
here's the code:
var db = Database.Open("StayInFlorida");
var proptype = db.Query("SELECT * FROM Property_Type");
IEnumerable<dynamic> queryResults;
//Search Variables
string searchTerm = "";
string resortID = "";
string propertyType = "";
string numBedrooms = "";
List<string> argList = new List<string>();
//Paging Variables
var pageSize = 6;
var totalPages = 0;
var count = 0;
var page = UrlData[0].IsInt() ? UrlData[0].AsInt() : 1;
var offset = (page -1) * pageSize;
//Request querystrings from URL
if (!String.IsNullOrWhiteSpace(Request.QueryString["searchTerm"]))
{
searchTerm = Request.QueryString["searchTerm"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["resortID"]))
{
resortID = Request.QueryString["resortID"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["propertyType"]))
{
propertyType = Request.QueryString["propertyType"];
}
if (!String.IsNullOrWhiteSpace(Request.QueryString["numBedrooms"]))
{
numBedrooms = Request.QueryString["numBedrooms"];
}
int numOfArguments = 0;
string selectQueryString = "SELECT * FROM Property_Info ";
if (searchTerm != "")
{
argList.Add(searchTerm);
selectQueryString += "WHERE FullDescription LIKE '%' + #0 + '%' OR BriefDescription LIKE '%' + #0 + '%' ";
numOfArguments++; //increment numOfArguments by 1
}
if (resortID != "")
{
argList.Add(resortID);
if (numOfArguments == 0)
{
selectQueryString += "WHERE ResortID = #0 ";
}
else
{
selectQueryString += "AND ResortID = #" + numOfArguments + " ";
}
numOfArguments++;
}
if (propertyType != "")
{
argList.Add(propertyType);
if (numOfArguments == 0)
{
selectQueryString += "WHERE PropertyTypeID = #0 ";
}
else
{
selectQueryString += "AND PropertyTypeID = #" + numOfArguments + " ";
}
numOfArguments++;
}
if (numBedrooms != "")
{
argList.Add(numBedrooms);
if (numOfArguments == 0)
{
selectQueryString += "WHERE NumBedrooms = #0 ";
}
else
{
selectQueryString += "AND NumBedrooms = #" + numOfArguments + " ";
}
numOfArguments++;
}
selectQueryString += "ORDER BY CreatedDate DESC";
string[] argArray = argList.ToArray();
queryResults = db.Query(selectQueryString, argArray);
count = queryResults.Count();
totalPages = count/pageSize;
if(count % pageSize > 0){
totalPages += 1;
}
Edited code after Polynomial's suggestion:
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Search Page";
var db = Database.Open("StayInFlorida");
var proptype = db.Query("SELECT * FROM Property_Type");
//Paging Variables
var pageSize = 6;
var totalPages = 0;
var count = 0;
var page = UrlData[0].IsInt() ? UrlData[0].AsInt() : 1;
var offset = (page -1) * pageSize;
IEnumerable<dynamic> queryResults;
//Request querystrings from URL
string selectQueryString = "SELECT * FROM Property_Info WHERE 0 = 0 AND NumBedrooms = #0 AND NumBathrooms = #1 ";
selectQueryString += "ORDER BY CreatedDate DESC";
queryResults = db.Query(selectQueryString, Request.QueryString["NumBedrooms"], Request.QueryString["NumBathrooms"]);
count = queryResults.Count();
totalPages = count/pageSize;
if(count % pageSize > 0){
totalPages += 1;
}
}
Well, there are lots of ways around the problem, I'm thinking the easiest one that doesn't involve not using named ordinal parameterization would be to use fixed ordinals for each search criteria and just not use the ones you don't need in the SQL statement. Your code is very long so I don't really want to try and rewrite the whole thing here, but basically if your db.Query() call has all of the potential arguments passed as parameters like this:
queryResults = db.Query(selectQueryString, Request.QueryString["searchTerm"], Request.QueryString["resortId"]).AsInt(), Request.QueryString["propertyType"].AsInt() /* etc etc */);
Then your ordinals are always the same number. searchTerm is always #0, resortId is always #1 etc, etc. You then don't need the array at all and just need to build up an appropriate SQL statement for what the user specified, for example some WHERE clauses that would all fit with the code above could be:
"WHERE ResortID = #1"
"WHERE PropertyType = #2"
"WHERE ResortID = #1 AND PropertyType = #2"
"WHERE Name = #0"
"WHERE Name = #0 AND ResortID = #1 AND PropertyType = #2"
In the case of the clauses that only use one or two of the parameters, the others are just ignored and hopefully everything will work as you intend.
Edit to show code:
// Basic beginning of the select statement
string selectQueryString = "SELECT * FROM Property_Info WHERE 0 = 0 ";
// Check to see if the user specified bedrooms, if they did add to the select statement
if (Request.QueryString["NumBedrooms"].AsInt() > 0)
{
selectQueryString += "AND NumBedrooms = #0 ";
}
// Same for the number of bathrooms
if (Request.QueryString["NumBathrooms"].AsInt() > 0)
{
selectQueryString += "AND NumBathrooms = #1 ";
}
// ** Add more criteria to your select list here by checking for valid values and concatenating your string **
// Finally add the order by on the end
selectQueryString += "ORDER BY CreatedDate DESC";
// Execute the statement
queryResults = db.Query(selectQueryString, Request.QueryString["NumBedrooms"].AsInt(), Request.QueryString["NumBathrooms"].AsInt());
This should give you a very flexible and expandable search criteria system that is happy with zero, one or many criteria.