How to write a do while loop which ask user to try again if answer is incorrect?
Q: How to write a do while loop which ask user to try again if answer is incorrect?
Ans :
import java.io.*;
import java.util.Scanner;
class AskUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ans = "", play = "";
Pattern p = new Pattern();
do {
p.question();
ans = sc.nextLine();
if(ans != "a" || ans != "b" || ans != "c" || ans != "d") {
if(ans.equals("c")) {
System.out.println("correct answer!");
break;
} else {
System.out.println("incorrect! try again!");
System.out.print("Press y to continue : ");
play = sc.nextLine();
}
} else {
System.out.print("Press y to continue : ");
play = sc.nextLine();
}
} while (play.equals("y") || play.equals("Y"));
}
public void question() {
System.out.println("What is the command key to exit a loop in java?");
System.out.println("A : int");
System.out.println("B : continue");
System.out.println("C : break");
System.out.println("D : exit");
System.out.print("your answer : ");
}
}
Ans :
import java.io.*;
import java.util.Scanner;
class AskUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ans = "", play = "";
Pattern p = new Pattern();
do {
p.question();
ans = sc.nextLine();
if(ans != "a" || ans != "b" || ans != "c" || ans != "d") {
if(ans.equals("c")) {
System.out.println("correct answer!");
break;
} else {
System.out.println("incorrect! try again!");
System.out.print("Press y to continue : ");
play = sc.nextLine();
}
} else {
System.out.print("Press y to continue : ");
play = sc.nextLine();
}
} while (play.equals("y") || play.equals("Y"));
}
public void question() {
System.out.println("What is the command key to exit a loop in java?");
System.out.println("A : int");
System.out.println("B : continue");
System.out.println("C : break");
System.out.println("D : exit");
System.out.print("your answer : ");
}
}
Comments
Post a Comment