Why does BlueJ say that modulo isn't a statement? - modulo

For school I have to make a little program that makes Ticket Id's. One task says: "The ticket ID is the age modulo the length of the first name + the length of the last name. I've tried this:
TicketID = firstname + lastname;
TicketID.length() % age;
I get the error that the % is not a statement.
If you could help me that would be amazing.

You need to assign the result of % to some other variable
TicketID = firstname + lastname;
(here) = TicketID.length() % age;

Related

Remove words except last one in String

I have a String with different value every time:
String words = "My name is Rob Joe";
I want to get only last word
Joe
but every time I don't know how many words the string consists of
String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'
In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
String words = "My name is Rob Joe";
List<String> wordsArray = myString.split(" ");
String lastWord = wordsArray[wordsArray.length - 1];
print(lastWord); // "Joe"
Instead of splitting, you can also use substring and lastIndexOf:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") + 1);
print(lastWord);
If you want to find the last word, you should first properly define what a "word" is.
It's clearly obvious here, which is why it's doubly important to write it down, because something else may be just as obvious to someone else.
(Read: Nothing is obvious. Document it all!)
But let's say that a word is a maximal contiguous sequence of ASCII letters.
Then that's what you should look for.
Splitting on space characters works for this string, but won't if you have punctuation, or trailing whitespace, or any number of other complications.
I'd probably use a RegExp:
// Matches a word. If used properly, only matches entire words.
var wordRE = RegExp(r"[a-zA-Z]+");
// Assume at least one word in `words`. Otherwise need more error handling.
var lastWord = wordRe.allMatches(words).last[0]!;
This can be a little inefficient, if the string is long.
Another approach that might be more efficient, depending on the RegExp implementation, is to search backwards:
/// Captures first sequence of [a-zA-Z]+ looking backwards from end.
var lastWordRE = RegExp(r"$(?<=([a-zA-Z]+)[^a-zA-Z]*)");
var lastWord = lastWordRE.firstMatch(words)?[1]!;
If you don't want to rely on RegExps (which are admittedly not that readable, and their performance is not always predictable), you can search for letters manually:
String? lastWord(String words) {
var cursor = words.length;
while (--cursor >= 0) {
if (_isLetter(words, cursor)) {
var start = 0;
var end = cursor + 1;
while (--cursor >= 0) {
if (!_isLetter(words, prev)) {
start = cursor + 1;
break;
}
}
return words.substring(start, end);
}
}
return null;
}
bool _isLetter(String string, int index) {
var char = string.codeUnitAt(index) | 0x20; // lower-case if letter.
return char >= 0x61 /*a*/ && char <= 0x7a /*z*/;
}
But first of all, decide what a word is.
Some very real words in common sentences might contain, e.g., ' or -, but whether they matter to you or not depends on your use-case.
More exotic cases may need you to decide whether"e.g." is one word or two? Is and/or? Is i18n?
Depends on what it'll be used for.

casting MapValue to double and multiply to double in dart

Iam new to dart I want a Make table of food program which take an input from user for each food and how much they want but i have an problem with multiply listOfFood[name] with count which both of them double is there any way to solve this ?
double name , count ;
Map<String , dynamic> listOfFood = {
'bacon' :'4.2',
'salad' :'3.5',
'cheaken' :'5.6',
'Goatmeat' :'6.9',
'fish' : '6.5',
};
Map<int , dynamic> food = {
1 : listOfFood ['bacon']
,2 : listOfFood ['salad']
,3 : listOfFood ['cheaken']
,4 : listOfFood ['Goatmeat']
,5 : listOfFood ['fish']
};
stdout.write('please Choose your product \n ${listOfFood}');
name = double.parse(stdin.readLineSync()!);
count = double.parse(stdin.readLineSync()!);
double result = (food[name]) * count;
print(result);
}
You cannot coerce a String that looks like a number to a double in Dart.
Dart has strong typing even when you declare a variable dynamic.
In your case, you're taking the value from listOfFood (not a List, use a better name like priceByFoodName), which is always a String (despite the Map having dynamic values) and multiplying that with a double which can't work.
You should ask yourself why are the prices Strings?
If you want to use them as numbers, just make them numbers.
Also, you don't need dynamic at all. Use types! If you had done that the compiler would've told you right away what the problem was before you even ran the code. That's why types exist.
To solve the problem quickly... this line:
double result = (food[name]) * count;
Should be changed to:
double result = double.parse(food[name]!) * count;
But you should probably change your code quite a bit to handle errors, use appropriate types, stop ignoring nulls etc.

Regex to allow only numbers and +, -, () for number phone

[DataType(DataType.PhoneNumber)]
[RegularExpression("^([0-9 .()-+)$", ErrorMessage = CommonConstants.PhoneError)]
public string PhoneNumber { get; set; }
I have a PhoneNumber field. With this field I want to give a permission for user, just type number or +,-,),(.
How can I have a RegularExpression ?
Your current regex has an unterminated character group ([ with no ]). You want something like this:
^([\d() +-]+)$
Note the order of + and - - - is a range indicator, so it needs to be first, last, or escaped (as in \-).
Here's a demo.

specifying min length if field has data

I need to control a field with a min length if someone enters a value but if they don't enter anything in, I don't want the form to tell them there is a min value.
This is what I have:
[Required]
[StringLength(15, ErrorMessage = "Please supply at least {2} characters.", MinimumLength = 3)]
[Display(Name = "Last name on account or first part of the company's name")]
public string LastName { get; set; }
I just need for it to allow blanks also or if data is entered, require it to be a min of 3 characters..
Any suggestions?
The problem is with the validation logic of the StringLength attribute, that returns true also for the string with null value, here the implementation:
public override bool IsValid(object value)
{
this.EnsureLegalLengths();
int num = value == null ? 0 : ((string) value).Length;
if (value == null)
return true;
if (num >= this.MinimumLength)
return num <= this.MaximumLength;
else
return false;
}
Also the Required attribute that you used is not helping :-).
Anyway the only thing you can do for your scenario is to create a custom attribute to validate LastName with the logic that you need, here a link to an MVC3 example, or you can try googling, there is a lot of examples and is not hard to implement.

MVC .net annotation-based valiadation : Remove dashes and parenthesis from phone numbers

Is it possible to both validate, that the provided data is in the form of a phone number AND trim it down to just the numbers in the validator?
Input: (902) 837-2832
Output: VALID: YES, 9028372832
Or do I have to convert the input to the number-only format after the fact?
Add a property to your model with only a getter that returns the stripped down version of the property that is bound to the input. Put your validation attribute on that property.
public string PhoneNumber {get;set;}
[Required(ErrorMessage="Phone number is required.")]
[RegularExpression(#"\d{10}", ErrorMessage="Phone number is invalid.")]
public string PhoneNumberValue
{
get
{
var temp = PhoneNumber
temp = Regex.Replace(temp, #"[^0-9]", "");
temp = temp.Length == 11 && temp.StartsWith("1")
? temp.Substring(1) : temp;
}
set
{
// I can't remember off the top of my head if MVC model
// binding requires a setter or not. If so, just leave this
// empty. Otherwise you can remove it entirely.
}
}
Then, in your view, just render the alternate validation message.
#Html.LabelFor(x=>x.PhoneNumber)
#Html.TextBoxFor(x=>x.PhoneNumber)
#Html.ValidationMessageFor(x=>x.PhoneNumberValue)
Here is an example how to validate with Regular expression:
[Required(ErrorMessage="Phone Number is required")]
[RegularExpression("^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage="Not a valid number")]
public string PhoneNumber { get; set; }
We may use Trim method of string to clean the phone number and get only digits.
char[] charsToTrim = { '(', ' ', ')', '-'};
string phoneNumber = "(123)-345-6789";
string result = banner.Trim(charsToTrim);
Finally here is a post that explains Enabling Validation using DataAnnotations in more detail

Resources