I try to have this enhanced for loop of a Java code in my C# code:
for (float value : array) {
if (Float.isInfinite(value) || Float.isNaN(value)) {
value = 0;
}
}
I tried this out:
foreach (float value in array)
{
if (float.IsInfinity(value) || float.IsNaN(value))
{
value = 0;
}
}
But I have this error that told me I have not the right to modify value because it is an iteration variable.
You need to use a normal for loop if you want to update the iterator variable:
for(int i = 0 ; i < array.Length; i++)
{
if (float.IsInfinity(array[i]) || float.IsNaN(array[i]))
{
array[i] = 0;
}
}
From C# specifications:
The iteration variable corresponds to a read-only local variable with
a scope that extends over the embedded statement. During execution of
a foreach statement, the iteration variable represents the collection
element for which an iteration is currently being performed. A
compile-time error occurs if the embedded statement attempts to modify
the iteration variable (via assignment or the ++ and -- operators) or
pass the iteration variable as a ref or out parameter.
Related
protected Day[] days= new Day[n];
for(int i=0;i<days.length; i++)
{
days[i]= new Day(5);
}
Above mentioned code works fine for me but modified for loop as mentioned below results in NullPointerException when I try to access the elements of the array. Can anyone explain why does it happens?
protected Day[] days= new Day[n];
for(Day d:days)
{
d= new Day(5);
}
When Java sees the enhanced for loop that you've made, it runs whatever you put inside it and makes a new variable (called d) and gives this variable a value of whatever is inside of your array. When you set d equal to a new Day(5); you are changing the value of the variable d, not the value inside the array. Here is a workaround:
protected D[] days = new Day [n];
for(int i = 0;i<days.length;i++)
days[i] = new Day(5);
This reaches into the actual array to set values. Hope this helps!
Loop variable in enhanced for loop is temporary. Assigning it inside loop body has no effect on the original item. Here is what happens to the loop according to Java Language Specification:
Day[] days = ...
for (int i = 0; i < days.length; i++) {
Day d = days[i];
...
}
When you assign d, it changes the local variable d, not days[i], which isnearly always an error. For that reason, some programming shops adopt a practice of making loop variable of enhanced for loop final:
for(final Day d:days) {
d= new Day(5); // <<== Compile-time error
}
If you want to shorten the code by avoiding the loop, use
Arrays.setAll(days, i -> new Day(5));
Second type of for uses Iterator for iterating by elements. Initializing reference d makes no sence, because this operation doesn't change reference inside your array.
Write a static method method call longCount, which is passed an array of strings, and which returns the number of strings in the array that are more than 10 characters long (and thus the method return type is int). You must use a for-each loop in your solution.
This is what I came up with although it is still not compiling when I submit it.
public static int longCount(int[] data){
int count = 0;
for(int n : data){
if(data[n]>10)
count++;
}
return count;
}
Your method is supposed to accept a String[], not an int[]. That's probably what's causing the compiler error (but it's hard to tell, since you don't report the error message.) Also, the for-each loop for arrays binds the loop variable to each array value, not each index. I'd rewrite your method as:
public static int longCount(String[] data) {
int count = 0;
for (String s : data){
if (s.length() > 10) {
count++;
}
}
return count;
}
To guard against array elements being null, you might consider changing the if condition to
if (s != null && s.length() > 10) {
Change
if(data[n]>10)
to
if(n>10)
with the for-each loop you get the value (not the index).
In terms of style or performance, is it better to define variables within loops or outside of them?
For example:
int var;
for (...) {
var = /*something*/;
// Code that uses var
}
or
for (...) {
int var = /*something*/;
// Code that uses var
}
If you have any insight on how variable declarations work internally, and how one of these might perform better than the other (even if it's only slightly), please share. And outside of performance, which style is preferred?
Inside
for(int i = 0; i < array.length; i++) {
final String variable = array[i];
}
Keeps scope of variables limited.
Variable can be final
More readable (maybe)
Outside
String variable;
for(int i = 0; i < array.length; i++) {
variable = array[i];
}
Variable is accessible outside loop.
For Each
for(final String variable : array) {
}
Only allocates once (source needed)
Keeps scope of variable limited.
Looks frickin' awesome.
Performance
The following test was run. It takes approximately 30s to run. The results show that there is no difference in performance between defining the variable inside or outside of the loop. This is most likely due to compiler optimizations. YMMV.
final double MAX = 1e7;
long start = System.nanoTime();
String var1;
for(double i = 0; i < MAX; i++) {
var1 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);
start = System.nanoTime();
for(double i = 0; i < MAX; i++) {
final String var2 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);
Discussion of Style Preference: https://stackoverflow.com/a/8803806/1669208
You should define for loop initialization variables in for loop header only which limits its scope within the loop. If you are concerned about performance then you should define variables within the loop.
Define variable outside loop only if you are using value of that variable outside loop as well.
Well, depends on how the variable is intended to be used primarily, if you are defining a variable inside a loop you would need to initialize the variable before the first use of the variable and in every run of the loop the variable would be re-initialized to this value.
On the other hand if you want to value of the variable to persist among different runs in the loop then you have to declare it outside. I don't think performance and style could be the primary criteria here.
If you declare the variable inside the for loop you won't be able to access it outside the loop.
for (...) {
int var = /*something*/;
// Code that uses var
}
you cannot access var outside the loop.
int var;
for(...) {
var = /*something*/;
// Code that uses var
}
var can be accessed outside the loop. Any other class code can use the value of var being set in the for loop.
Bottom line it all depends on your requirements.
The only time you should try to move the variable outside the loop, even if it's never used outside the loop is if you can re-use an object, and avoid using new on every iteration of the loop.
StringBuilder builder = new StringBuilder();
for(...) {
builder.append(..);
builder.append(..);
strings[i] = builder.toString();
// reset builder, to be used again
builder.setLength(0);
}
This is much more efficient than making a new StringBuilder every time.
In all other cases, you should prefer to declare variables inside the loop if you can
I was optimizing an application and wanted to change my for loops to enhanced loops:
From:
for (int m = 1;m < MAX_BEREN;m++)
{
Wasberen[m] = new Wasbeer();
Wasberen[m].YYY = r.nextInt(SchermY - 28);
}
to:
for (Wasbeer a : Wasberen)
{
if (a!=null)
{
a = new Wasbeer();
a.YYY = r.nextInt(SchermY - 28);
}
}
I get a NullPointerException, because it probably doesnt know how much 'beren' can be in
the array, but I'm not sure how to manage the same as the loop above (MAX_BEREN = 11).
If the array reference ('Wasberen' in this case) in an enhanced for statement is null, then a NullPointerException will result when the statement is executed.
For initializing arrays, you should stick to the syntax you had before.
You can't use the enhanced for-loop in Java to fill an array. (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.)
Your code (simplified)
for (Wasbeer a : Wasberen)
{
a = ...;
}
is equivalent to
for (int i = 0; i < Wasberen.length; i++)
{
Wasbeer a = Wasberen[i];
a = ...;
}
This assignment will change the local variable a, but will have no effect on the contents of the array.
Is it different than C or C#?
Java has one keyword, for, but it can be used in two different manner:
/* classical, C/C++ school */
for (int i = 0; i < N; i++) {
}
for-each style:
// more object oriented, since you use implicitly an Iterator
// without exposing any representation details
for (String a : anyIterable) {
}
it works for any type that implements Iterable<String> such as List<String>, Set<String>, etc.
The latter form works also for arrays, see this question for a more "phisophical approach".
The following demonstrates the syntax of a java for loop (from the for loop in Java):
class Hello {
public static void main (String args[]) {
System.out.print("Hello "); // Say Hello
for (int i = 0; i < args.length; i = i + 1) { // Test and Loop
System.out.print(args[i]);
System.out.print(" ");
}
System.out.println(); // Finish the line
}
}
Also see the Wiki entry on For loop
The only difference between java's for-loop syntax and C's is you can declare variables in the initialization field (1st section) of the loop