Return value after Try statement - return

Only recently started doing code so be gentle and have been given a a very simple assignment from my college.
private static double getNumber()
{
double value1;
Console.WriteLine("please enter your first number");
try
{
value1 = double.Parse(Console.ReadLine());
return value1;
}
catch
{
Console.WriteLine("Must be numeric");
}
I've tried putting the return value1 all over the place however i keep getting the error message Program.getNumber()': not all code paths return a value.
Thoughts?

You should have return statement in you catch block as well.

Just put return outside the block:
private static double getNumber()
{
double value1 = 0;
Console.WriteLine("please enter your first number");
try
{
value1 = double.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Must be numeric");
}
return value1;
}
It will occure whenever try passed or caught.

private static double getNumber()
{
double value1=0;
Console.WriteLine("please enter your first number");
try
{
value1 = double.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Must be numeric");
}
return value1;
}

Related

Conditional member access for map children?

Lets say you are trying to access deeply nested children in a map and you are not able to expect their parents to be there. Example:
Map awesomeMap = {
"this":{
"is":{
"sometimes":"not here"
}
}
}
Map notAwesomeMap = {
"this":{
"haha":{
"we":"switched"
}
}
}
When I go to access notAwesomeMap['this']['is']['sometimes'] it will return an error because ['this']['is'] is null, and you cannot look for the value ['sometimes'] of null.
So that's fine, but I was hoping to be able to use conditional member access operators...
notAwesomeMap['this']?.['is']?.['sometimes']
but that doesn't work...
Short of wrapping everything in a try block, is there a good way to handle these situations?
Edit: I tried playing around with this and I didn't find anything really illuminating, but maybe this gives someone an idea
void main() {
Map nestedMap = {
'this':{
'is':{
'sometimes':'here'
}
}
};
final mapResult = nestedMap['this'];
print(mapResult); //returns {is: {sometimes: here}}
final nullResult = nestedMap['this']['is an'];
print(nullResult); // returns null
final nullifiedResult = nullify(nestedMap['this']['is an']['error']);
print(nullifiedResult); // returns error, but is this possible another way?
final errorResult = nestedMap['this']['is an']['error'];
print(errorResult); // returns error
}
nullify(object){
try {
final result = object;
return result;
}
catch (e) {
return null;
}
}
One way would be
final result = (((nestedMap ?? const {})['this'] ?? const {})['is an'] ?? const {})['error'];
See also Null-aware operator with Maps
You could write a simple function to help do what you want:
R lookup<R, K>(Map<K, dynamic> map, Iterable<K> keys, [R defaultTo]);
Example usage:
final result = lookup(inputMap, ['this', 'is', 'something']);
Example implementation:
https://dartpad.dartlang.org/1a937b2d8cdde68e6d6f14d216e4c291
void main() {
var nestedMap = {
'this':{
'is':{
'sometimes':'here'
}
}
};
print(lookup(nestedMap, ['this']));
print(lookup(nestedMap, ['this', 'is']));
print(lookup(nestedMap, ['this', 'is', 'sometimes']));
print(lookup(nestedMap, ['this', 'is', 'error']));
// Bail out on null:
print(lookup(nestedMap, ['error'], 'Default Value'));
}
R lookup<R, K>(Map<K, dynamic> map, Iterable<K> keys, [R defaultTo]) {
dynamic current = map;
for (final key in keys) {
if (current is Map<K, dynamic>) {
current = current[key];
} else {
return defaultTo;
}
}
return current as R;
}
I like #matanlurey's approach, but have made two changes:
Drop the defaultTo since you can still use ?? which is more readable.
Swallow type-cast errors.
R lookup <R, K>(Map<K, dynamic> map, Iterable<K> keys) {
dynamic current = map;
for (final key in keys) {
if (current is Map<K, dynamic>) {
current = current[key];
}
}
try{
return current as R;
} catch(e){
// do nothing
}
}
Usage is similar
String someValue = lookup(nestedMap, ['some', 'value']) ?? 'Default Value';

Boolean method not retuning correct value

Ok so I think I'm being a noob because it's a new semester but the method "palindromeTest" always return's false even though the string is equal and the number is a palindrome. (A palindrome example is: (565) 677-6565) (also don't give me the answer outright I want to solve it on my own)
public class IjazZ_PhoneStringPalindrome
{
public static void main(String[] args) throws IOException
{
String phoneNumber;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a phone number in this format (###) ###-####: ");
phoneNumber = br.readLine();
phoneNumber = justNumbers(phoneNumber);
if (palindromeTest(phoneNumber))
{
System.out.println("This phone number is a palindrome!");
}
else
{
System.out.println("This phone number is not a palindrome!");
}
}
public static String justNumbers(String phoneNumber)
{
StringTokenizer st = new StringTokenizer(phoneNumber, " ()-");
StringBuffer number = new StringBuffer();
while(st.hasMoreTokens())
{
number.append(st.nextToken());
}
phoneNumber = number.toString();
return phoneNumber;
}
public static boolean palindromeTest(String pNumber)
{
StringBuffer reversedNumber = new StringBuffer(pNumber);
reversedNumber.reverse().toString();
if(pNumber.equals(reversedNumber))
{
return true;
}
else
{
return false;
}
}
}
You don't assign the value returned by reversedNumber.reverse().toString()to reversedNumber.
Do
String reversedNumberString = reversedNumber.reverse().toString();
And by the way, you can just return
return pNumber.equals(reversedNumber); - the if/else statement is unnecessary.

Code equivalent of out or reference parameters in Dart

In Dart, how would I best code the equivalent of an (immutable/value/non-object) out or reference parameter?
For example in C#-ish I might code:
function void example()
{
int result = 0;
if (tryFindResult(anObject, ref result))
processResult(result);
else
processForNoResult();
}
function bool tryFindResult(Object obj, ref int result)
{
if (obj.Contains("what I'm looking for"))
{
result = aValue;
return true;
}
return false;
}
This is not possible in Dart. Support for struct value types, ref or val keywords were discussed on the Dart mailing list just like week. Here is a link to the discussion where you should let your desire be known:
https://groups.google.com/a/dartlang.org/d/topic/misc/iP5TiJMW1F8/discussion
The Dart-way would be:
void example() {
List result = tryFindResult(anObject);
if (result[0]) {
processResult(result[1]);
} else {
processForNoResult();
}
}
List tryFindResult(Object obj) {
if (obj.contains("What I'm looking for")) {
return [true, aValue];
}
return [false, null];
}
you can also use a tuple package like tuple-2.0.0
add tuple: ^2.0.0
to your pubspec.yaml
then any function can return many typed objects like this:
import 'package:tuple/tuple.dart';
Tuple3<int, String, bool?>? returnMany() {
return ok ? Tuple3(5, "OK", null) : null;
}
var str = returnMany().item2;
In your case:
void example() {
var result = tryFindResult(anObject);
if (result.item1) {
processResult(result.item2!);
} else {
processForNoResult();
}
}
Tuple2<bool, int?> tryFindResult(Object obj) {
if (obj.contains("What I'm looking for")) {
return Tuple2(true, aValue);
}
return Tuple2(false, null);
}
you can throw an exception too when no result.
void example() {
var result = tryFindResult(anObject);
try {
processResult(result);
} on NullException catch(e){
processForNoResult();
}
}
int tryFindResult(Object obj) { // throws NullException
if (obj.contains("What I'm looking for")) {
return aValue;
}
throw NullException();
}

Comma separation in the Text Field in Blackberry

in my application i have a Custom text box with BasicEditField.FILTER_NUMERIC. When the user enter the value in the field the comma should be added to the Currency format .
EX:1,234,567,8.... like this.
In my code i tried like this.
protected boolean keyUp(int keycode, int time) {
String entireText = getText();
if (!entireText.equals(new String(""))) {
double val = Double.parseDouble(entireText);
String txt = Utile.formatNumber(val, 3, ",");// this will give the //comma separation format
setText(txt);// set the value in the text box
}
return super.keyUp(keycode, time);
}
it will give the correct number format... when i set the value in the text box it will through the IllegalArgumentException. I know BasicEditField.FILTER_NUMERIC will not allow the charector like comma(,)..
How can i achieve this?
I tried this way and it works fine...
public class MyTextfilter extends TextFilter {
private static TextFilter _tf = TextFilter.get(TextFilter.REAL_NUMERIC);
public char convert(char character, int status) {
char c = 0;
c = _tf.convert(character, status);
if (c != 0) {
return c;
}
return 0;
}
public boolean validate(char character) {
if (character == Characters.COMMA) {
return true;
}
boolean b = _tf.validate(character);
if (b) {
return true;
}
return false;
}
}
and call like this
editField.setFilter(new MyTextfilter());

how to set a BasicEditField to accept dotted decimal numbers

I have added a BasicEditField to a GridFieldManager. When I test it, it allows input values like 11.11.11. How can I make my BasicEditField accept only correct double numbers, like 101.1 or 123.123. That is, allow only one decimal point.
gfm = new GridFieldManager(1, 2, 0);
gfm.add(new LabelField(" Enter value : "));
bef = new BasicEditField(BasicEditField.NO_NEWLINE|BasicEditField.FILTER_REAL_NUMERIC);
bef.setFilter(TextFilter.get(NumericTextFilter.REAL_NUMERIC));
bef.setFilter(TextFilter.get(TextFilter.REAL_NUMERIC));
bef.setText("1");
bef.setMaxSize(8);
gfm.add(bef);
add(gfm);
i had tried everything that i can. but the problem is yet in my app. can anyone give me a proper way to design a input field tha accepts decimal numbers?
Please add all the objects into the mainScreen with add(field);.
and then trying to get value of that fields.
now in your code put
String s = bef.getText();
Dialog.alert(s);
after
add(gfm);
and
To accept number like 1.1111.
then add
BasicEditField.FILTER_REAL_NUMERIC
in BasicEditFieldConstructor.
Now i think you got your solution.
finally i got the solution for a forum(forgot to copy the link)..
here it is...
inside my class i put the variables...
private int maxIntDigits = -1;
private int maxFractDigits = -1;
private String old;
i had added a BasicEditField, bef..
bef = new BasicEditField("","1");
bef.setMaxSize(8);
bef.setChangeListener(this);
add(bef);
And then in its fieldChanged().
public void fieldChanged(Field field, int context)
{
if(field==bef)
{
String str = bef.getText();
if(str.equals(""))
{
old = "";
//return;
}
if(str.indexOf('.') == str.lastIndexOf('.'))
{
if(str.indexOf('-') >= 0)
{
bef.setText(old);
}
if(validateIntPart(str) && validateFractPart(str))
{
old = str;
//return;
}
else
{
bef.setText(old);
}
}
else
{
bef.setText(old);
//return;
}
}
}
and then two functions in it...
private boolean validateIntPart(String str) {
if(maxIntDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
p = str.length();
}
int digits = str.substring(0, p).length();
if(digits > maxIntDigits) {
return false;
} else {
return true;
}
}
private boolean validateFractPart(String str) {
if(maxFractDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
return true; //if no '.' found then the fract part can't be too big
}
int digits = str.substring(p + 1, str.length()).length();
if(digits > maxFractDigits) {
return false;
} else {
return true;
}
}

Resources