Which code should you insert at line 03?

You are creating a console application named App1.
App1 will validate user input for order entries.
You are developing the following code segment (line numbers are included for reference only):

You need to complete the code segment.
The solution must ensure that prices are positive and have two decimal places.
Which code should you insert at line 03?

You are creating a console application named App1.
App1 will validate user input for order entries.
You are developing the following code segment (line numbers are included for reference only):

You need to complete the code segment.
The solution must ensure that prices are positive and have two decimal places.
Which code should you insert at line 03?

A.
Option A

B.
Option B

C.
Option C

D.
Option D

Explanation:
* Regex.IsMatch Method (String, String)
Indicates whether the specified regular expression finds a match in the specified input string.
Syntax:
public static bool IsMatch(
string input,
string pattern
)



Leave a Reply 9

Your email address will not be published. Required fields are marked *


delfigaro

delfigaro

Correct answer is C!!!
^(-)?\d+(.\d\d)?$ allows for negative numbers because of the (-) group
^\d+(.\d\d)?$ only allows positive numbers

both with 2 decimals though

kasp

kasp

C looks the best option however if we press just for example 5 it returns “valid” even though we didn’t enter any decimal points. I think the correct solution would be

Regex reg = new Regex(@”^\d+(\.\d\d)$”);
if (reg.IsMatch(price))

Just need to take out the ?

J

J

@kasp: Your analysis is correct.

anii

anii

Could it also be

if(Regex.IsMatch(price, @”^\d+(\.\d\d)$”);

?

Like in B, but with correct pattern…

anii

anii

correction:

if(Regex.IsMatch(price, @”^\d+(\.\d\d)$”));

So, could it?

Leonardo

Leonardo

Option C

rao

rao

C seems to be CORRECT.

public class Program
{

static void Main(string[] args)
{
Console.WriteLine(“Enter unit price:”);
string price = Console.ReadLine();
Regex reg = new Regex(@”^\d+(\.\d\d)?$”);
if (reg.IsMatch(price))
Console.WriteLine(“OK”);
else
Console.WriteLine(“WRONG”);
Console.ReadKey();
}
}

Béni

Béni

C is indeed the right answer; with answer B, the “^(-)?” means “if there’s a ‘-‘ at the beginning of the line, capture it. It doesn’t mean “exclude ‘-‘ at the beginning of the line”.
To exclude a set of char, specifically ‘-‘ in our case, we must use [^-].
\d means “a digit” so as delfigaro mentionned, it automatically excludes the ‘-‘ char.