Reputation: 83
I'm in a stuck with do-while looping that requires looping with do-while until users input one of three correct strings
I've tried with this
Scanner input = new Scanner(System.in);
String motor = "motor";
String mobil = "mobil";
String kosong = "";
String baru = "baru";
int tahun = Calendar.getInstance().get(Calendar.YEAR);
do {
inputVehicleType();
vehicleCondition = input.next();
}
while (!(vehicleCondition.equals(motor)) || (vehicleCondition.equals(mobil)) || (vehicleCondition.equals(kosong)));
System.out.println("SUCCED");
private static void inputVehicleType() {
System.out.println(Constant.HEADER);
System.out.println("Input Jenis Kendaraan Mobil/Motor --> (jenis [motor/mobil])");
titleFooter();
}
with that syntax it only retrieve (vehicleCondition.equals(motor). My expected result was it can retrieve (vehicleCondition.equals(motor), (vehicleCondition.equals(mobil), (vehicleCondition.equals(kosong).
Upvotes: 1
Views: 128
Reputation: 9766
Make a method to check the condition:
private static boolean isValidVehiculeCondition(String vc) {
return !Arrays.asList("motor", "mobil", "baru").contains(vc.toLowerCase());
}
Then loop while it returns true (ie: input is not valid)
do {
inputVehicleType();
} while(isNotValidVehiculeCondition(input.next()));
Upvotes: 0
Reputation: 1
I think you have a little parenthesis mistake in your code. You need to add an extra parenthesis around not operator. Your condition should be
while (!(
(vehicleCondition.equals(motor)) ||
(vehicleCondition.equals(mobil)) || (vehicleCondition.equals(kosong))
));
Upvotes: 0
Reputation: 340
You have made a mistake in your while logic expression
should be:
while (!((vehicleCondition.equals(motor)) || (vehicleCondition.equals(mobil)) || (vehicleCondition.equals(kosong))));
Upvotes: 3
Reputation: 361849
If you remove the excess parentheses it may be easier to spot that you have while (!a || b || c)
instead of while (!(a || b || c))
.
do {
...
} while (!(vehicleCondition.equals(motor) ||
vehicleCondition.equals(mobil) ||
vehicleCondition.equals(kosong)));
Or, equivalently via De Morgan's laws, while (!a && !b && !c)
:
do {
...
} while (!vehicleCondition.equals(motor) &&
!vehicleCondition.equals(mobil) &&
!vehicleCondition.equals(kosong));
Upvotes: 5
Reputation: 393936
The correct condition would be:
while (!(vehicleCondition.equals(motor) ||
vehicleCondition.equals(mobil) ||
vehicleCondition.equals(kosong)));
i.e. you should stay in the loop as long as vehicleCondition
is not equal to one of the 3 expected values.
Upvotes: 1