Hey im very new at java so please bear with me :)
I have objects v1, v2, v3 with each one containing details of soccer players stats
int LessThan25 = 0;
for (int i = 0; i < topscorer.size(); i++)
{
while (v**[i]**.getGoals() < 25)
{
LessThan25++;
}
}
My question is that how do I make this loop work? I want to be able to use the integers in the for loop for my while v loop which links to my class definition. (bolded part)
Appreciate the help :)
I get what you mean now, you can do this to access each topScorer object:
for(int x=0; x<topScorer.size(); x++) //iterate through all elements in topScorer
if(topScorer.get(x).getGoals() < 25)
lessThan25++;
The syntax to access the elements within an ArrayList is:
list.get(x) where x is the element you wanted to access (starts from 0)
Alternatively:
Certainly, enhanced for-loop (for each loop works too):
for(Scorer s : topScorer) //Scorer is the object type in your list
if(s.getGoals() < 25)
lessThan25++;
Use 'if' condition instead of 'while', i think that is what you looking.
Use the enhanced for loop - a better idiom if using Java 5+.
Variable names should start lower case by convention.
for(Player player : players) {
if(player.getGoals < 25)
lowerThan25Goals++;
}
The answer of user3437460 is what you're looking for
for(Scorer s : topScorer)
if(s.getGoals() < 25)
lessThan25++;
An example of a Player would have been nice,
sth. like
Player cRonaldo = new Player(age, size, avgGoals, (total)goals);
Player lMessi = new Player(age, size, avgGoals, (total)goals);
Please, take a look at your while-loop
while (topScorer[i].getGoals() < 25)
{
LessThan25++;
}
This is an infinit loop. Becaue if u ever reach the point where a topScorer aka v [i] has less than '25' goals, u never get that loop to stop, and your counter LessThan25 breaking the limit of your ALU ;)
( lower case variables! )
Could be a mistake, or missing code you provided.
So just for you, being 'new' to Java, to know.
If you're using Java 8, you can easily solve this problem using Stream API in only one line of code:
long lessThan25 = topScorer.stream()
.filter(element -> element.getGoals() < 25).count();
Moreover, using Streams the JVM can improve performance in background.
Related
int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be
so if c is less than 20, it repeats the operation "c=+(a+1);" until it breaks out of the loop by c>=20.
this is a simplified code from my program, mine is GUI. every time I run the code, it freezes.
use c+= instead of c=+. try that, cheers!
and b+= instead ofb=+.
You can tag a loop and do break or continue instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto instruction. You can only switch the flow inside loops by those instructions.
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
You're probably very new to the language. Welcome!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. Based on your description of numbering your lines and the fact that you have the statement:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. This is not the case. The iterator i is a variable that simply holds an integer (just like a, b, and c in your code).
I suggest you take a look at a tutorial on for loops. It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually).
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6.
I have a Collection of objects I need to iterate over. The collection is of variable size. If the collection has more than 1 object in it, I need to perform special processing on objects 2 .. infinity.
What's the preferred method to do this? For example:
int count = 1;
for (CustomObject co : CustomObjectCollection) {
methodAll(co);
if(count > 1) {
methodSpecial(co);
}
count = count++;
}
What you have will work except for one bug: count = count++ does absolutely nothing. count = count + 1 would work, or count++, but count = count++ is a no-op.
You could also just use a boolean flag if you don't specifically need to track the count.
boolean first = true;
for (CustomObject co : CustomObjectCollection) {
methodAll(co);
if (!first) {
methodSpecial(co);
}
first = false;
}
Which to use
Which to use depends on your specific use case. Assuming that you are not looking to optimise every last op-per-second of performance then go with the option that declares your intent:
count++ is fine if you want to track or use the count outside the loop (as per Louis' answer, it is count++, not count = count++)
for(int i = 0; i < collection.size(); i++) is good as well if the collection supports a get(i) operation. This also lets you skip the first item by initialising int i to a different index. It might be used if you don't want the extra count variable hanging around outside the loop.
the above boolean first = true; (or the inverse boolean notFirst = false;) highlight that you want to treat the first and subsequent elements differently
If you have the List interface on your collection and want to skip a set number of elements, then subList is a good option
Performance
If performance is a concern, then measure it for your platform and implementation, but from general experience, from slowest to fastest, with <=20x difference between the first and last:
for each loop with iterator: slowest
for(int i = 0; i < list.size() ; i++)
declare int size = list.size() then a for(int i = 0; i < size; i++) loop
However these speed results depend on so many things that unless performance is a design goal or an identified issue go with the iterator until you have a reason to use one of the other two - the iterator is generally fast enough.
I think a better way to do this would be to work directly with the iterator like so:
Iterator<CustomObject> it = customObjectCollection.iterator();
if(it.hasNext()) { //first pass don't call methodSpecial
methodAll(it.next());
}
CustomObject customObj;
while(it.hasNext()) { //all the rest 2..infinity
customObj = it.next();
methodAll(customObj);
methodSpecial(customObj);
}
customObj = null; // for garbage collection
This way you don't have to check each iteration if this is the first run or not.
This will work with any Iterable (which is already needed for a foreach loop anyway).
Note: If this is not an ordered collection you might get different elements in the first iteration then you might expect.
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
I have an array with 5 size , and I want to assign value from random function if any index doesn't have it.
while(positionXtoStart==array1[0] || positionXtoStart==array1[1] ||
positionXtoStart==array1[2] || positionXtoStart==array1[3] ||
positionXtoStart==array1[4])
{
positionXtoStart = (rand1.nextInt(400) + 1)+30;
}
this solution is ok for small size of array but if i have array with size of 1000, I cant enter 1000 conditions in the while loop.
I tried For-loop with if-else condition in it but the
problem is, I want to check all array indexes at the same time.
Please try to understand what i am asking. I want to check all array index values at the same time (in one shot).
in For-loop, we can check only one value at a time.
If I understand correctly, you just need to loop through the array, checking each value.
for (int i = 0; i < array1.length; i++)
{
if (array1[i] == positionXtoStart)
{
positionXtoStart = (rand1.nextInt(400) + 1)+30;
break; // exit the loop
}
}
are you looking for something like this?
for(int i=0; i<array1.length; i++)
if(array[i] == whatever)
{
// do stuff
}
unfortunately, what you're asking is not possible. Even in your code:
while(positionXtoStart==array1[0] || positionXtoStart==array1[1] ||
positionXtoStart==array1[2] || positionXtoStart==array1[3] ||
positionXtoStart==array1[4])
the computer is checking one condition at a time. It's not doing all the conditions at once, like you may think it is. The code you posted is equivalent to the code #Supericy and #Samiam posted.
Unless there's a reason the forloops doesn't work for your case, I would say go with the answers that are posted here.
If you have to check each entry you have to go trough the whole array. An unordered array in not really suitable for searching trough it. Maybe you should think of changing your data structure into something like a BST so you have a guarantied O(logn) search.
To compare all elements in an unordered array you need linear time.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Break from main/outer loop in a double/nested loop?
I have the following situation:
for(int i = 0; i < schiffe.length-1; i++){
if(schiffe[i].schaden){
schlepper.fliege(schiffe[i].x,
schiffe[i].y,
schiffe[i].z);
schlepper.wirdAbgeschleppt = schiffe[i];
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
break;
}
}
}
}
I want to
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
be performed once and then break out of the inner loop and continue with the for(int i... loop. So I used a break in my code. But I am not really sure if this is right. Does the break cause a break for all loops or just for the second loop?
It breaks only the inner loop, and therefore does what you want. To break more than one level, in Java, you can use a "labelled break" like so:
schiffe_loop:
for(int i = 0; i < schiffe.length-1; i++){
some_stuff();
for(int k = 0; k < stationen.length-1; k++){
if (something_really_bad_happened()) {
break schiffe_loop;
}
}
}
But usually you will not need this.
You may consider making a separate method for the inner loop anyway; it's something you can easily give a name to ("find_available_station" or something like that), and will probably need somewhere else.
Also, please be aware that your loops right now will miss the last element of each array. Think carefully about why you are using < instead of <=; it's exactly so that you use every value from 0 up to but not including the specified one.
break will break the innermost loop, in your case 2nd loop.
To make it break the outer loop you can use a labeled break as:
OUTER:for(...) {
for(...) {
break OUTER;
}
}
break only breaks out of the innermost loop.
break will cause break for closest loop only (second loop)
Just the second one. You can use "goto" of course.
Break statement terminates the closest enclosing loop or switch statement in which it appears in many languages but you can try it and be sure 100%.
put the inner two loops in a function and use return to break out of both of them.
If you need more control, you can use a labeled break. More info here. As others have said, break will close the closest loop.
What about using a boolean you call 'found' and use it like this:
while(!found) {
for(...) {
//todo
}
}
I Think You Can Do One More Thing..
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
k = stationen.length + 1 ;
}
}