How to simplify multiple if else statement using Java - regex

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;
}

Related

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
}
}

How to perform other operations when my tokenizer recognizes a token?

I have written a simple tokenizer that will split a command line into seperate lines each containing a single word. I am trying to ...
Make the program close if the first word of a command line is "quit"
Recognize instructions such as "Pickup", "Save", and "Go" in which the compiler will then look to the next token.
My idea has been to use a simple switch with cases to check for these commands, but I cannot figure out where to place it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char command[256];
int commandIndex;
char token[32];
int isWhiteSpace(char character) {
if (character == ' ') {
return 1;
}
else if(character == '\t') {
return 1;
}
else if(character < ' ') {
return 1;
}
else {
return 0;
}
} char* getToken() {
int index = 0; // Skip white spaces
while(commandIndex<256 && isWhiteSpace(command[commandIndex])) {
commandIndex ++;
} // If at end of line return empty token
if(commandIndex>=256) {
token[0] = 0;
return token;
} // Capture token
while(commandIndex<256 && !isWhiteSpace(command[commandIndex])) {
token[index] = command[commandIndex];
index++;
commandIndex ++;
}
token[index] = 0;
return token;
}
void main() {
printf("Zeta - Version 2.0\n");
while(1) {
printf("Command: ");
gets_s(command);
commandIndex = 0;
char* token = getToken();
while (strcmp(token,"") != 0) {
printf("%s\n", token);
token = getToken();
}
}
}
A little reorganization of the loop you have in main will do it.
int main() {
printf("Zeta - Version 2.0\n");
bool done = false;
while (!done) {
printf("Command: ");
gets_s(command);
commandIndex = 0;
char* token = getToken();
if (strcmp(token, "quit") == 0) {
done = true;
} else if (strcmp(token, "pickup") == 0) {
doPickup();
} else if (strcmp(token, "save") == 0) {
char * filename = getToken();
doSave(filename);
} ...
}
return 0;
}
You can't use a switch statement with strings, so you just use a bunch of if ... else if ... statements to check for each command. There are other approaches, but this one required the fewest changes from the code you already have.
In the example, under the handling for "save" I showed how you can just call getToken again to get the next token on the same command line.
(Note that I also fixed the return value for main. Some compilers will let you use void, but that's not standard so it's best if you don't do that.)

Testing if the string meets the Right format C++

I am currently trying to test if a read in string matches the following format, without the use of regex.
The format the code should be in, is:
Supplier Reference: XXXXXXX
Date & Time: XXXX
Name of Device: XXXXX
Priority: X
IP Address: XXXXXXXXXXXXXXXXXXXX
Event ID: XXXXXX
Description of Event: XXXXXXXXXXXX
I want the code to have a cout << "Format is incorrect" << endl;.
This is edit, taken out previous attempt and gone back to basics to explain my logic:
using namespace std;
int f;
int main()
{
string mystring;
ifstream myfile ("test.txt");
if (myfile.is_open())
{ while (getline (myfile,mystring))
{
//searches the text entered//
string search;
size_t pos;
{
//searches the text for the Date entry//
{
search = "Supplier Reference:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f=f-1;
}
else
{
++f;
}
}
}
{
search = "Date & Time:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
{
search = "Name of Device:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
{
search = "Priority:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
{
search = "IP Address";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
{
search = "Event ID:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
{
search = "Description of Event:";
pos = mystring.find(search);
{
if (pos != string::npos)
{
cout<<mystring<<endl;
f = f - 1;
}
else
{
++f;
}
}
}
}
}
{
if (f>35)
cout << f << "Field is missing, Ticket is formatted incorrectly" << endl;
}
}
system ("pause");
return 0;
}
I know the code is incredibly repetitive. Cheep and Cheerful is what I'm aiming for.
I was hoping someone could let me know how to test for the order of the lines?
One way to solve this is to read seven lines (one for each line of data). If a line is empty, then discard it and don't count it.
Then for each line, you split it into two strings at the colon ':'. Use the left part (e.g. "Supplier Reference") as the key into a std::map with the right part as data.
Then just loop over the map and make sure that each key matches the needed keys from the file. If a key is missing, or an unknown key is in the map (or if there are not enough lines when reading from the file) your have a format error.

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

Shunting Yard algorithm implementation

I've been trying to implement shunting yard algorithm. The code gets an input from the user and after it is evaluated by another function (which is done already), it will be converted to postfix notation and then passed to be computed. The code below is just for the algorithm itself. ie is the vector of tokens made from user's input.
The code makes sense to me but it doesn't compile, yet can't figure out where is not quite right.
double eval_infix_expr(vector<Token> ie, map<string,double> sym_tab)
{
vector<Token> postfix_expr;
static bool IsOperator(const string& token) {
return token == "+" ||
token == "-" ||
token == "*" ||
token == "/" ||
token == "%";
}
static int PrecedenceOf(const string& token) {
if (token == "+" || token == "-") return 0;
if (token == "*" || token == "/" || token == "%") return 1;
throw runtime_error("Unknown operator: " + token);
}
bool expectingOperator = false;
for (size_t i = 0; i < ie.size(); ++i) {
if (IsOperator(ie[i])) {
if (!expectingOperator)
throw runtime_error("Unexpected operator: " + ie[i]);
while (!sym_tab.empty() && IsOperator(sym_tab.top()) &&
PrecedenceOf(sym_tab.top()) >= PrecedenceOf(ie[i])) {
postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
}
sym_tab.push(ie[i]);
expectingOperator = false;
}
else if (ie[i] == "(") {
if (expectingOperator)
throw runtime_error("Expected operator, found (.");
sym_tab.push(ie[i]);
}
else if (ie[i] == ")") {
if (!expectingOperator)
throw runtime_error("Expected value, found ).");
while (!sym_tab.empty() && sym_tab.top() != "(") {
postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
}
if (sym_tab.empty())
throw runtime_error("Imbalanced parentheses.");
sym_tab.pop();
expectingOperator = true;
}
else {
if (expectingOperator)
throw runtime_error("Expecting operator, found " + ie[i]);
postfix_expr.push_back(ie[i]);
expectingOperator = true;
}
}
if (!expectingOperator)
throw runtime_error("Expected value, didn't find one.");
while (!sym_tab.empty()) {
if (sym_tab.top() == "(")
throw runtime_error("Imbalanced parentheses.");
postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
}
}
postfix_Evaluator pe(postfix_expr);
return pe.eval();
}
}