Reputation: 85
I'm trying to print out a result based on 2 variables. I have an array 8 elements long...
a
, which is calculated separately. If a is between certain values then it prints out the result.I've tried breaking out of multiple loops but when I run the program, sometimems depending on input im getting "Loser" and "Decent" printed out together, when I expect only one of the two.
outerloop:
for (int i = 0; i < array.length; i++)
{
if (module[i] < 40 )
{
System.out.println("Loser");
}
else
{
if (a >= 0 && a < 40)
{
System.out.println("Loser");
}
else if (a >= 40 && a < 60)
{
System.out.println("Decent");
}
else if (a >= 60)
{
System.out.println("Leet");
}
}
break outerloop;
}
Upvotes: 1
Views: 136
Reputation: 11114
You can't check them within the same loop easily. I'd break it up. Off the top of my head:
boolean loser = false;
for (int i = 0; i < array.length && !loser; i++) {
if (module[i] < 40 || a < 40) {
System.out.println("Loser");
loser = true;
}
}
if (!loser) {
if (a >= 40 && a < 60) {
System.out.println("Decent");
}
else if (a >= 60) {
System.out.println("Leet");
}
}
Upvotes: 2
Reputation: 1270
You've got quite a problem here: an array of values which you want to 'score' as a group.
If any value is < 40, you want to stop looking and print 'loser'.
If the current value is >= 40, you need to keep looking because the next value might be < 40;
however, you also want to know if there is a 'leet' score somewhere in the array.
So:
boolean loser = false, leet = false;
for( int i = 0; i < array.length; ++i ) {
if( array[i] < 40 ) {
loser = true;
break;
}
// if it's not < 40, it must be more
// now check if it qualifies as leet
if( array[i] > 60 ) {
leet = true;
}
}
if( loser ) {
print loser
} else if( leet ) {
print leet
} else {
print decent
}
Upvotes: 0
Reputation: 3767
Don't use labels for control flow. Instead, put the functionality into a separate method.
Java is not meant to be used like Fortran or Basic which use goto
's to move to various points in a program, which is typically written in a single scope. Like this:
function(){
section1: if(condition) goto section2
section2: if(condition) goto sectionN
....
sectionN: if(condition) goto section1
}
Java is typically organized more like
java.exe:Main{
Class(){
classRelatedMethod(){
Class(){ ... // recursive definition }
}
}
}
This allow each class
to define reusable, discrete pieces of functionality that are coupled to each other. Where they are not, a new class
should be defined. While many other languages (including Fortran and BASIC) can accomplish this, Java was designed from the ground up with this in mind (along with being a platform independent language as well, but that's not quite the same thing.)
All of this is pretty academic and can be found with Google pretty easily.
Upvotes: 0