For-loop condition conventions [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I had recently a discussion about the use of non-counter related conditions in for-loops in Java:
for(int i = 0; o.getC() < 10; i++)
o.addC(i);
Does anyone know if there are any "official" conventions for for-conditions like this? In my opinion it's easier to read compared to an equivalent while-loop because all loop-parameters are together in the first line:
int i = 0;
while(o.getC() < 10) {
i++;
o.addC(i);
}
Or even worse:
int i = 0;
while(o.getC() < 10)
o.addC(++i);

for loops are used in pretty much every situation over equivalent while solution. Arrays, lists, standard data structures.
On the other hand while is commonly used with streams and for infinitely long iterations..

Most developers will expect a for statement to consist of three things:
Initialization of a variable
Termination condition based on the variable
Increment on the variable
If you change your code to contain unexpected things it will get harder to read and thus harder to maintain.
Furthermore, I think the while loop makes your intention clearer: do something while o.getC() is less then 10. This "something" happens to be: add an incrementing number.
Long story short: use a while loop for "non-counter related conditions".

A nice thing about for loops is there is a shortcut method. So if you want to do all of the items in an array you can just do the following:
(double number : arrayName)
where double is the type, number is the name you are giving each element (it doesn't matter really what you call it, you will refer to each value there as "number" in this case). And arrayName is the name of the array you are referring to.
If you want to reach each element/object this is the fastest way.

How about:
for(int i = 0; i < MAX_ITERATIONS; i++)
{
o.addC(i);
if (o.getC() >= 10)
return o; // or break
}
This prevents an infinite loop if addC is not really doing what you expect.

Related

Is there a way to do many similar tasks in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
Say for instance I want to repeat the line of code
Integer int1 = new Integer(value1);
for many variables, such as int1 to int100. I am not asking about this exact task in particular - I am asking about any such situation where the code would be identical save for replacing small details like int1 and value1 with int2, value2. Is there a way to have the JVM complete this for me?
I am not even sure what approach to take on this or what term to search for more information. The only thing I can think to try is instead of typing "int1", having a loop that changes a string containing the name and attempting to pass the string as a symbol to the JVM but this of course does not work.
It was a little strange question and I don't know if I understood your meaning correctly or not.
But in this particular case, instead of repeating the code, you can use a data structure like an array. See Oracle tutorial.
int[] numvar = new int[arr.length];
for (int i = 0; i < args.length; i++) {
int someNumber = Integer.parseInt(args[i]);
numvar[i] = someNumber;
}

Should I put if(variable < 10) in own method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a check in a loop where I have to check if the number of occurrence is less than 10 which could be written as either
if(occ < 10){
}
or
if(checkIfOccurencyIsLessThan10(occ)){
values.add(current+"0"+occ);
}
else{
values.add(current+occ);
}
I'm reading Clean Code a handbook of agile software craftsmanship, where they say a method should do the least amount, and code should be hacked up into more pieces. Is this necessary right here? I'm trying to get a better grasp on how long a method should be, and how much it should be doing.
It depends on if this condition is spread across multiple pieces of code, and if this check could change in the future to include checking additional edge cases. If both of those things are true or could be true, then sure, extracting the check to its own function is wise. However, I would definitely say you should rename the function to not specify the functions implementation, because that defeats the purpose of being able to change out the conditional, right? Naming it something like occurenceNeedsZero is a much more flexible solution. Because if you come up with other use cases that need checking you can add them to this function as well!
However, if your question is "should I always make a simple conditional check such as "is x < 10" into its own function, then I would say no. That would be overengineering, in my opinion. Functions should be used to 1) separate logical portions of code, 2) increase readability, or 3) extract small pieces of code that are spread across multiple locations and likely to change in the future, as it simplifies future refactoring.
There are probably more cases than those 3, but those are the big ones.
It's better to use a static final variable to store this 10, instead hard code.
If there are other places need to check if occ < 10, you need extract it as a method. Otherwise it is unecessary.

Can somebody please tell me how to translate this equation into a Java process? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know how to translate this:
into a Java process that looks like:
public static float computeAverage(float [] i){
//I have no idea what this is supposed to be.
}
or perhaps even
public static double computeAverage(double [] i){
//Still have no idea what this is meant to be.
}
If it's easier to answer with doubles, that's fine, but I really don't need that level of precision.
*Edit:*Okay, tell me if this looks right:
public static float computeAverage(float [] i){
float tally = 0f;
for(int x=0;x<i.length;x++){
tally = tally + pValue(i[x]);
}
return tally / i.length;
}
public static float pValue(float i){
return 2 - 1f/i;
}
I don't want to do your work right away, because it won't help you in the future. But I'll try to give you hints.
Java elements
The different elements that you might need are the following:
the number n, which is the number of elements in your input array, can be accessed using myInput.length
to iterate with a moving k index, you'll need a for loop. Check this out to know how to use for loops.
you'll have to be careful that in Java, arrays are indexed starting at 0, not 1. So to access Ck, you'll actually write myInput[k-1].
Break down your problem
What do you want to achieve? You're not just "translating this formula into Java code", but you're writing a method (a function) which, given an input array of Ci, returns an average following the specified formula.
I think your assignment is to write the following function:
Maybe you should try to:
write a little method for p()
write a for loop that performs a sum (the internet is full of these)
adapt your for loop using p()
divide the result of the for loop by n
return the divided result
UPDATE: it's much easier to help you once you've tried something :)
Your code looks fine overall now. According to your formula I think you're adding the wrong value to the sum in your loop).
It should probably be: tally = tally + pValue(i[x])

Looping: i vs loopCount [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it better to use the variable 'i' or a meaningful name such as 'loopCount' or 'studentsCount' etc?
e.g.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5; j++)
{
System.out.println(i + j);
} // End of j loop
} // End of i loop
VS
for (int outerLoop = 0; outerLoop < 10; outerLoop++)
{
for (int innerLoop = 0; innerLoop < 5; innerLoop++)
{
System.out.println(outerLoop + innerLoop);
} // End of innerLoop
} // End of outerLoop
By better; the main considerations would be readability / conventions.
Related question Loop iterator naming convention
EDIT:
I have tagged this a java, but answers for other languages are welcome.
Firstly, using Integer here is very expensive because Integer is immutable. Thus each time you do an increment it unboxes the previous Integer, do an increment and creates another Integer to hold the new value. You need to use int.
Secondly, whether to have a readable name really up to the semantics of the int. If it's just a control variable over a pre-determined number of loops I think i is fine; but if it has specific meaning then you are free to give it a better meaningful name.
Code is communication: what do you want the reader of this code (who might be you months or years from now) to think when he sees it? To me, using "i" and "j" in a loop says "do this thing 10 times; the variable is just a convention and means nothing", while using a more descriptive variable like "studentID" says "this number actually refers to something specific" I'd use the former if I want to de-emphasize the variable itself, and the latter if I want to highlight it.
I have seen many loops that started out small and grew very large with other loops added inside and around them and it all became a confusing mess of i j k x y z. Name your references with the shortest name that expresses your intent, so another dev will know what you were going for.
Traditionally i and j are used for this type of thing, but there's certainly nothing wrong with giving them a meaningful name to aid in readability. If I were reading another persons code, I would rather prefer outer/innerloop to i and j.
Use i and j if you want. People reading your code will probably decode these to be the names of loop variables, and if they can't, then shame on them.
(( if you use long names for loop variables in a language where long names will hinder performance, then I'll slap you ))
In the looping you can use i , j (not meaningful name) and the program will compile and run.
But in the big project if you use i, j , this is only know you. Other person who is your leader difficult to understand your code. That why you should make habit even there are not big project.
Thank you
i and j origin in mathematical conventions for matrices, as a form of abstraction. I use it mainly in an math/numeric algorithm context.

Is it bad style to not use the loop variable in for-each statements in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is it considered poor style / discourage to ignore the loop variable in a for-each statement in Java?
I have some code looks looks sort of like the following:
public void makeChecklist( final List<File> inputSrcs ){
for( File src : inputSrcs ){
System.out.print( src.getName() + "\t" );
}
System.out.println();
for( File src : inputSrcs ){
//Not using "src" in this body!
System.out.print( "[ ]\t" );
}
System.out.println();
}
Is this a bad idea? Any reason not todo things this way? It just seems so much cleaner than using a regular for-loop.
PS- presume that for the example above I want the checkboxes to appear underneath the names, the example is contrived to ilustrate my question as simply as possible.
It certainly looks odd. I would make it clearer that it's only the count that matters with a for loop:
for (int i = 0; i < inputSrcs.size(); i++) {
System.out.println( "[ ]\t" );
}
I think that makes the intention clearer. Although as has been pointed out in the comments, we're really just replacing one "dummy" variable with another in the above. What I like about it is that it explicitly calls size(), which I believe shows that the size is important.
In a more expressive language you might find something to indicate "I just want to execute the body n times" which would be prettier still:
inputSrcs.size().times() {
System.out.println( "[ ]\t" );
}
(That may or may not be valid Groovy :)
EDIT: Another obvious answer occurs to me, which should have occurred before:
printRepeatedly("[ ]\t", inputSrcs.size());
...
private static void printRepeatedly(String text, int count) {
for (int i = 0; i < count; i++) {
System.out.println(text);
}
}
Now in the calling method, the meaning is absolutely obvious... and within printRepeatedly we don't even have the context of a list, so we couldn't possibly be trying to use the data. At this point the dummy variable i is fairly obviously a dummy variable, and the method name makes it obvious why we'd want this behaviour.
I think if you're going to do it, the comment removes a lot of the ambiguity/potential confusion.
Seems perfectly clear to me.
You will find that the line feeds added by println()--as opposed to print()--will make it so your check boxes aren't really lining up with anything other than your left margin.

Categories

Resources