software testing
Suppose we have the following text-based menu. We want to use a while loop to get an integer (i.e., 1, 2 or 3) from the user, and prompt to input again if an invalid number is received. Which loop(s) in A, B, C and D can achieve that? (There can be more than 1 correct choice.)
A: do{ System.out.println(“Please input 1, 2 or 3”); //let the user to input a number, choice will hold the input. }while((choice != 1) || (choice != 2) || (choice != 3));
B:
do{
System.out.println(“Please input 1, 2 or 3”);
//let the user to input a number, choice will hold the input.
}while((choice == 1) || (choice == 2) || (choice == 3));
C: do{ System.out.println(“Please input 1, 2 or 3”); //let the user to input a number, choice will hold the input. }while(!((choice==1)||(choice==2)||(choice==3)));
D:
do{
System.out.println(“Please input 1, 2 or 3”);
//let the user to input a number, choice will hold the input.
}while((choice!=1)&&(choice!=2)&&(choice!=3));
This question requires me to select the correct answer
First,we need to know how to use do while loop sentence,It first executes the statement in the loop, then decides whether the expression is true, continues the loop if it is true, and terminates the loop if it is false.
We can use two examples to test this question,we use choice==2 and choice ==4,we expect that choice == 2 ,it should quit the loop,and choice == 4 it would continue the loop
Let's see A,(choice != 1) || (choice != 2) || (choice != 3) ,it is obviously that choice == 2 satisfied the choice!=1,so it would continue the loop,which is wrong
Let's see B, (choice == 1) || (choice == 2) || (choice == 3), it is obviously that choice == 2 satisfied the choice == 2 , so it would continue the loop, which is wrong
Let's see C , !((choice==1)||(choice==2)||(choice==3)) , it is obviously that choice ==2 not satisfied ,because it means that choice should !=1 && !=2 && !=3 , so choice == 4 satisfied , so it would continue the loop ,which is correct
Let's see D, (choice!=1)&&(choice!=2)&&(choice!=3) , it is obviously that choice == 2 not satisfied ,and choice == 4 is satisfied ,so it is correct
So ,I will choose C and D
Draw flow graphs for the following 3 code fragments.