I am working with an API that uses functions that use out parameters. I want to use the value in one of these out parameters in a while loop. For example:
static int counter = 0;
static void getCounterValue(out int val)
{
val = counter;
counter++;
}
static void Main()
{
// Right now, I'm having to do this:
int checkVal = 0; // I have to figure out an appropriate starting value.
while (checkVal < 10)
{
getCounterValue(out checkVal);
Console.WriteLine("Still waiting.");
}
Console.WriteLine("Done.");
}
Is there a simpler syntax to do this? I want something more classic like while (getCounterValue() < 10), but I have to deal with the out parameters because it's an API that I can't change.
You can't do anything directly, the return value of the method call is what while will use and that can't be the value you want. If this is causing you problems, you can always wrap the method call:
int wrappedGetCounterValue()
{
int i;
getCounterValue(out i);
return i;
}
Or with C# 7:
int wrappedGetCounterValue()
{
getCounterValue(out int i);
return i;
}
And use that in your while loop.
while (wrappedGetCounterValue() < 10)
....
do
{
getCounterValue(out checkVal);
Console.WriteLine("Still waiting.");
} while (checkVal < 10)
You can use the infinite loop with break condition:
while (true)
{
int checkVal;
getCounterValue(out checkVal);
if (10 <= checkVal)
break;
Console.WriteLine("Still waiting.");
}
Note the difference between do..while (checkVal < 10) option is that you will not output "Still waiting" message if first counter value will be greater or equal to 10. You cannot do that with do..while loop unless you will duplicate loop break condition (checkVal < 10).
Another option (but with the cost of code duplication) is to use for loop:
int checkVal;
for (getCounterValue(out checkVal); checkVal < 10; getCounterValue(out checkVal))
{
Console.WriteLine("Still waiting.");
}
Console.WriteLine("Done.");
If you want to completely hide the out functionality you must use a wrapper method. If you care only for "valid" values and the validity is well-defined by the <10 expression, then you can hide the <10 expression in that wrapper, and use a Nullable<int> in your code. That would be semantically correct.
static int counter = 0;
static void getCounterValue(out int val)
{
val = counter;
counter++;
}
static Nullable<int> getValidCounterValue()
{
int outResult;
getCounterValue(out outResult);
if (outResult < 10)
{
return null;
}
else
{
return outResult;
}
}
static void Main()
{
Nullable<int> checkVal = new Nullable<int>();
while (!checkVal.HasValue)
{
checkVal = getValidCounterValue();
Console.WriteLine("Still waiting.");
}
Console.WriteLine("Done. Valid value is:" + checkVal.Value.ToString());
}
I've tried google, and the advance search here. No luck.
Class SomeClass
{
public string MethodName()
{
//Some Code
While(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
}
}
I get a 'not all code paths return a value' error. I'm sure I can work around this but I'd like to know how to solve this for future reference.
Think if while loop condition is not met, would your method return string? So put the return just before end of method to ensure that your method will always return string, this MSDN error page not all code paths return a value would further help you to understand.
I believe the sample code is just to show the problem as it does not make much sense to me.
public string MethodName()
{
//Some Code
While(conditions) {
//More Code
string X;
X = "string stuff";
return X;
}
return "somestringifnotX";
}
You are getting error because you are trying to return value from while loop which is not possible
Problem here if your while loop condition is not satisfied than no value get return that is the reason compiler giving you error.
Solution to this is , return empty string outside while loop that you function is returning value.
public string functionname
{
while(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
return string.Empty;
}
The problem is that the compiler believes there is a path where conditions is NOT met on the first time it hits the while:
//Some Code
while(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
.. Problem!
return "not found"; // or throw new Exception("I'm not supposed to be here")
What you need to do is also return (or throw!) in the instance where conditions aren't met at all.
I think you mean this
static void Main(string[] args)
{
for (int i = 0; i < MethodName().Count; i++ )
{
var result = MethodName()[i] as string;
Console.WriteLine(result);
}
Console.ReadLine();
}
private static List<string> MethodName()
{
var items = new List<string>();
while (Condition)
{
items.Add("SString to return");
}
return items;
}
I hope it will help
Your problem is that you will not return anything when you don't pass your while loop
Class SomeClass
{
public string MethodName()
{
//Some Code
While(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
return "Nothing to return Actually";
//OR
Throw new Exception("Conditions where false");
}
}
Imagine you're conditions = false and you never entered the while. This means you will never get to the return. your function on the other hand needs one. End your statement with a return or throw an error when you don't want that behaviour.
public static string binarySearch(int [] dataArray, int dataDicari)
{
int first = 0;
int last = list.length – 1;
int mid;
while (first <= last)
{
mid = (first+last)/2;
if (dataArray[mid] == dataDicari)
return ......; //ISIAN 1
else if (dataArray[mid] < dataDicari)
first = mid + 1;
else if (dataArray[mid] > dataDicari)
last = mid – 1;
}
return .....; //ISIAN 2
}
I am using recursion to add two numbers together, By adding 1 to the first input one at a time until I have reached the value of the second.
Why does this work...
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
input1++;
input2--;
return AddMethod(input1, input2);
}
}
But not this..
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
return AddMethod(input1++, input2--);
}
}
I am using Visual Studio 2010 and .Net 4.0
Because return AddMethod(input1++, input2--); first passes your inputs, and THEN increments and decrements.
Try
return AddMethod(++input1, --input2);
Post fix increment works by first "assigning" the value, then incrementing the value.
Compare:
int a = 1;
int b = 1;
int x = a++;
int y = ++b;
So in your case, the value you pass to AddMethod is the unchanged value, it modifies the value of input1 and input2 after they are passed.
Because the ++ and -- operators are executed after passing the values as parameters to the function.
Your code:
return AddMethod(input1++, input2--);
Is equal to:
int result AddMethod(input1, input2);
input1++;
input2--;
return result;
Instead of all this, you could use:
return AddMethod(++input1, --input2);
I'm looking at the System.Threading.Tasks.TaskScheduler.Id implementation of .NET 4.0, and see the following code:
[__DynamicallyInvokable]
public int Id
{
[__DynamicallyInvokable]
get
{
if (this.m_taskSchedulerId == 0)
{
int num = 0;
do
{
num = Interlocked.Increment(ref s_taskSchedulerIdCounter);
}
while (num == 0);
Interlocked.CompareExchange(ref this.m_taskSchedulerId, num, 0);
}
return this.m_taskSchedulerId;
}
}
why does msft compare the num==0 after the interlocked? The implementation of Interlocked.Increment() says it returns the incremented value (after incrementing) so seems unnessicary to check for zero (unless your counter wraps around, but if that happens you have bigger problems that are also not resolved here.
If I were to do it, i'd simply do:
public int Id
{
get
{
if(m_taskSchedulerId==0)
{
var result = Interlocked.Increment(ref s_taskSchedulerIdCounter);
Interlocked.CompareExchange(ref m_taskSchedulerId, result, 0);
}
return m_taskSchedulerId;
}
}
but if that happens you have bigger problems
No, that's the exact reason they do this. From the Reference Source:
public Int32 Id
{
get
{
if (m_taskSchedulerId == 0)
{
int newId = 0;
// We need to repeat if Interlocked.Increment wraps around and returns 0.
// Otherwise next time this scheduler's Id is queried it will get a new value
do
{
newId = Interlocked.Increment(ref s_taskSchedulerIdCounter);
} while (newId == 0);
Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0);
}
return m_taskSchedulerId;
}
}
The invariant is that Id never returns 0, because 0 is used internally to indicate that the value should be initialized. If Id was ever 0, the next time you queried it it would be a different value.
In my limited experience, I've been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea has always been the same, however, the implementation has been different. Some surround a parse attempt with try/catch
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
and others match with regex
public boolean isInteger(String str) {
return str.matches("^-?[0-9]+(\\.[0-9]+)?$");
}
Is one of these methods better than the other? I personally prefer using the regex approach, as it's concise, but will it perform on par if called while iterating over, say, a list of a several hundred thousand strings?
Note: As I'm kinda new to the site I don't fully understand this Community Wiki business, so if this belongs there let me know, and I'll gladly move it.
EDIT:
With all the TryParse suggestions I ported Asaph's benchmark code (thanks for a great post!) to C# and added a TryParse method. And as it seems, the TryParse wins hands down. However, the try catch approach took a crazy amount of time. To the point of me thinking I did something wrong! I also updated regex to handle negatives and decimal points.
Results for updated, C# benchmark code:
00:00:51.7390000 for isIntegerParseInt
00:00:03.9110000 for isIntegerRegex
00:00:00.3500000 for isIntegerTryParse
Using:
static bool isIntegerParseInt(string str) {
try {
int.Parse(str);
return true;
} catch (FormatException e){}
return false;
}
static bool isIntegerRegex(string str) {
return Regex.Match(str, "^-?[0-9]+(\\.[0-9]+)?$").Success;
}
static bool isIntegerTryParse(string str) {
int bob;
return Int32.TryParse(str, out bob);
}
I just ran some benchmarks on the performance of these 2 methods (On Macbook Pro OSX Leopard Java 6). ParseInt is faster. Here is the output:
This operation took 1562 ms.
This operation took 2251 ms.
And here is my benchmark code:
public class IsIntegerPerformanceTest {
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
public static void main(String[] args) {
long starttime, endtime;
int iterations = 1000000;
starttime = System.currentTimeMillis();
for (int i=0; i<iterations; i++) {
isIntegerParseInt("123");
isIntegerParseInt("not an int");
isIntegerParseInt("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i=0; i<iterations; i++) {
isIntegerRegex("123");
isIntegerRegex("not an int");
isIntegerRegex("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took " + (endtime - starttime) + " ms.");
}
}
Also, note that your regex will reject negative numbers and the parseInt method will accept them.
Here is our way of doing this:
public boolean isNumeric(String string) throws IllegalArgumentException
{
boolean isnumeric = false;
if (string != null && !string.equals(""))
{
isnumeric = true;
char chars[] = string.toCharArray();
for(int d = 0; d < chars.length; d++)
{
isnumeric &= Character.isDigit(chars[d]);
if(!isnumeric)
break;
}
}
return isnumeric;
}
If absolute performance is key, and if you are just checking for integers (not floating point numbers) I suspect that iterating over each character in the string, returning false if you encounter something not in the range 0-9, will be fastest.
RegEx is a more general-purpose solution so will probably not perform as fast for that special case. A solution that throws an exception will have some extra overhead in that case. TryParse will be slightly slower if you don't actually care about the value of the number, just whether or not it is a number, since the conversion to a number must also take place.
For anything but an inner loop that's called many times, the differences between all of these options should be insignificant.
I needed to refactor code like yours to get rid of NumberFormatException. The refactored Code:
public static Integer parseInteger(final String str) {
if (str == null || str.isEmpty()) {
return null;
}
final Scanner sc = new Scanner(str);
return Integer.valueOf(sc.nextInt());
}
As a Java 1.4 guy, I didn't know about java.util.Scanner. I found this interesting article:
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java
I personaly liked the solution with the scanner, very compact and still readable.
Some languages, like C#, have a TryParse (or equivalent) that works fairly well for something like this.
public boolean IsInteger(string value)
{
int i;
return Int32.TryParse(value, i);
}
Personally I would do this if you really want to simplify it.
public boolean isInteger(string myValue)
{
int myIntValue;
return int.TryParse(myValue, myIntValue)
}
You could create an extension method for a string, and make the whole process look cleaner...
public static bool IsInt(this string str)
{
int i;
return int.TryParse(str, out i);
}
You could then do the following in your actual code...
if(myString.IsInt())....
Using .NET, you could do something like:
private bool isNumber(string str)
{
return str.Any(c => !char.IsDigit(c));
}
public static boolean CheckString(String myString) {
char[] digits;
digits = myString.toCharArray();
for (char div : digits) {// for each element div of type char in the digits collection (digits is a collection containing div elements).
try {
Double.parseDouble(myString);
System.out.println("All are numbers");
return true;
} catch (NumberFormatException e) {
if (Character.isDigit(div)) {
System.out.println("Not all are chars");
return false;
}
}
}
System.out.println("All are chars");
return true;
}
That's my implementation to check whether a string is made of digits:
public static boolean isNumeric(String string)
{
if (string == null)
{
throw new NullPointerException("The string must not be null!");
}
final int len = string.length();
if (len == 0)
{
return false;
}
for (int i = 0; i < len; ++i)
{
if (!Character.isDigit(string.charAt(i)))
{
return false;
}
}
return true;
}
I like code:
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
But it will good more when create Pattern before use it:
public static Pattern patternInteger = Pattern.compile("^[0-9]+$");
public static boolean isIntegerRegex(String str) {
return patternInteger.matcher(str).matches();
}
Apply by test we have result:
This operation isIntegerParseInt took 1313 ms.
This operation isIntegerRegex took 1178 ms.
This operation isIntegerRegexNew took 304 ms.
With:
public class IsIntegerPerformanceTest {
private static Pattern pattern = Pattern.compile("^[0-9]+$");
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
}
return false;
}
public static boolean isIntegerRegexNew(String str) {
return pattern.matcher(str).matches();
}
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
public static void main(String[] args) {
long starttime, endtime;
int iterations = 1000000;
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerParseInt("123");
isIntegerParseInt("not an int");
isIntegerParseInt("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation isIntegerParseInt took " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerRegex("123");
isIntegerRegex("not an int");
isIntegerRegex("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took isIntegerRegex " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerRegexNew("123");
isIntegerRegexNew("not an int");
isIntegerRegexNew("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took isIntegerRegexNew " + (endtime - starttime) + " ms.");
}
}
I think It could be faster than previous solutions if you do the following (Java):
public final static boolean isInteger(String in)
{
char c;
int length = in.length();
boolean ret = length > 0;
int i = ret && in.charAt(0) == '-' ? 1 : 0;
for (; ret && i < length; i++)
{
c = in.charAt(i);
ret = (c >= '0' && c <= '9');
}
return ret;
}
I ran the same code that Asaph ran and the result was:
This operation took 28 ms.
A huge difference (against 1691 ms and 2049 ms -on my computer). Take in account that this method does not validate if the string is null, so you should do that previously (including the String trimming)
I think people here is missing a point. The use of the same pattern repeatedly has a very easy optimization. Just use a singleton of the pattern. Doing it, in all my tests the try-catch approach never have a better benchmark than the pattern approach. With a success test try-catch takes twice the time, with a fail test it's 6 times slower.
public static final Pattern INT_PATTERN= Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");
public static boolean isInt(String s){
return INT_PATTERN.matcher(s).matches();
}
I use this but I liked Asaph's rigor in his post.
public static bool IsNumeric(object expression)
{
if (expression == null)
return false;
double number;
return Double.TryParse(Convert.ToString(expression, CultureInfo.InvariantCulture), NumberStyles.Any,
NumberFormatInfo.InvariantInfo, out number);
}
For long numbers use this:
(JAVA)
public static boolean isNumber(String string) {
try {
Long.parseLong(string);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isNumber(String str){
return str.matches("[0-9]*\\.[0-9]+");
}
to check whether number (including float, integer) or not
A modified version of my previous answer:
public static boolean isInteger(String in)
{
if (in != null)
{
char c;
int i = 0;
int l = in.length();
if (l > 0 && in.charAt(0) == '-')
{
i = 1;
}
if (l > i)
{
for (; i < l; i++)
{
c = in.charAt(i);
if (c < '0' || c > '9')
return false;
}
return true;
}
}
return false;
}
I just added this class to my utils:
public class TryParseLong {
private boolean isParseable;
private long value;
public TryParseLong(String toParse) {
try {
value = Long.parseLong(toParse);
isParseable = true;
} catch (NumberFormatException e) {
// Exception set to null to indicate it is deliberately
// being ignored, since the compensating action
// of clearing the parsable flag is being taken.
e = null;
isParseable = false;
}
}
public boolean isParsable() {
return isParseable;
}
public long getLong() {
return value;
}
}
To use it:
TryParseLong valueAsLong = new TryParseLong(value);
if (valueAsLong.isParsable()) {
...
// Do something with valueAsLong.getLong();
} else {
...
}
This only parses the value once.
It still makes use of the exception and control flow by exceptions, but at least it encapsulates that kind of code in a utility class, and code that uses it can work in a more normal way.
The problem with Java versus C#, is that C# has out values and pass by reference, so it can effectively return 2 pieces of information; the flag to indicate that something is parsable or not, and the actual parsed value. When we reutrn >1 value in Java, we need to create an object to hold them, so I took that approach and put the flag and the parsed value in an object.
Escape analysis is likely to handle this efficiently, and create the value and flag on the stack, and never create this object on the heap, so I think doing this will have minimal impact on performance.
To my thinking this gives about the optimal compromise between keeping control-flow-by-exception out your code, good performance, and not parsing the integer more than once.
public static boolean CheckIfNumber(String number){
for(int i = 0; i < number.length(); i++){
try{
Double.parseDouble(number.substring(i));
}catch(NumberFormatException ex){
return false;
}
}
return true;
}
I had this problem before but when I had input a number and then a character, it would still return true, I think this is the better way to do it. Just check if every char is a number. A little longer but it takes care if you have the situation of a user inputting "1abc". For some reason, when I tried to try and catch without iterating, it still thought it was a number so..