I have a problem with the case
del switch
: once they receive the parameter, eclipse tells me that the cases are duplicates. I paste the code; I would appreciate any suggestion to be able to group the number that the ramdom gives , group them in the case
:
do { num = (int)Math.random()*20+1;
switch (num) {
case 0-5:
edades.add(num);
grup1++;
break;
case 6-10:
edades.add(num);
grup2++;
break;
case 10-15:
edades.add(num);
grup3++;
break;
case 16-19:
edades.add(num);
grup4++;
break;
}// fin del switch
}while(num!=20);//fin del bucle do
I'm not very familiar with the latest versions of Java - read 11, 12, ... - but as far as I've been able to find out they haven't introduced ranged switches like the one you're trying to use.
What is happening is that the compiler evaluates the supposed ranges as the result of the subtraction of integers that you are putting, that is
With which you have a repeated case, the one associated with -5.
You can take a look at this StackOverflow question with several possible solutions. The simplest, although perhaps somewhat tedious and repetitive, would be
From what they point out in the comments of said question, it is expected that in the future if it allows this type of construction, this answer may be obsolete. But for that it is still missing. ;-P
By the way, beware that 10 appears in two of your ranks, the second and the third.
You are incorrectly using the
case
to take ranges.In java less than or equal to 11 the correct way to use
switch
is as follows:From java 12 onwards there is a big change in the use of
switch
although it can also continue to be used as previous versions.As you can see from java 12 if we want to use a range of
case
we can separate each case by a comma, another change is that it is no longer necessary to use thebreak
.You can also change
switch
to the conditionalif