There are two syntax errors in your code:
- The curly brace starting after
do
must end before while
, not after it.
throws FileNotFoundException
does not belong where it stands. You may have copied it from the declaration of the findInDataBase
method or elsewhere. Just delete it.
Edit:
findInDataBase
throws a FileNotFoundException
exception when an
item is not found in the database. It does not return a boolean. When
nothing is found, I want to return the confirmed unique term. How do I
complete the while statement?
Use a try
-catch
construct to see if the exception is thrown. And a boolean
variable to control the loop.
public String setNumber(ReportType type) {
Random rand = new Random();
String number = String.format("%02d", rand.nextInt(100));
String prefix = "";
String fullNumber;
boolean found;
do {
switch (type) {
case CHILD:
prefix = "A";
break;
case ELDER:
prefix = "B";
break;
case BOOMER:
prefix = "C";
break;
}
fullNumber = prefix + number;
try {
dataBase.findInDataBase(fullNumber);
found = true;
} catch (FileNotFoundException fnfe) {
found = false;
}
} while (found);
return fullNumber;
}
Alternative: The following might start an intense discussion since some find that it’s bad style. It simplifies a few things since it relieves us of having the two uninitialized variables declared before the loop.
public String setNumber(ReportType type) {
Random rand = new Random();
String number = String.format("%02d", rand.nextInt(100));
String prefix = "";
// This loop will be terminated by a return statement inside of it.
while (true) {
switch (type) {
case CHILD:
prefix = "A";
break;
case ELDER:
prefix = "B";
break;
case BOOMER:
prefix = "C";
break;
}
String fullNumber = prefix + number;
try {
dataBase.findInDataBase(fullNumber);
} catch (FileNotFoundException fnfe) {
// Nothing is found; return the confirmed unique term:
return fullNumber;
}
}
}
You are not out of problems yet. You will need to draw a new random number from rand
every time through the loop. Otherwise if the first number drawn is already in the database, you are in an infinite loop. If all 100 numbers from 00 through 99 are in use, you will be anyway.
Note: Since Java SE 14*, you can use the switch
expression instead of switch
statement.
do {
prefix = switch (type) {
case CHILD -> "A";
case ELDER -> "B";
case BOOMER -> "C";
};
fullNumber = prefix + number;
} while (dataBase.findInDataBase(fullNumber));
* The switch expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. You can check this Q/A to learn more about it.