Lukie Al-Saba Lukie Al-Saba - 2 months ago 10
Java Question

How can I create an if statement with 3 conditions? (Java)

I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.

import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;

class t1_lesson03_template{


public static void main (String str[]) throws IOException {

Scanner scan = new Scanner(System.in);

System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();

if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");

System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");

System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}

}

}

Answer

This,

else if (userinput1.equals(answer1) || userinput2.equals(answer2) 
    || userinput3.equals(answer3)) {

should be something like

else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
         (userinput1.equals(answer1) && userinput3.equals(answer3)) ||
         (userinput2.equals(answer2) && userinput3.equals(answer3))) {

but I would prefer a count. And an array to display your different messages. Something like

int count = 0;
if (userinput1.equals(answer1)) {
    count++;
}
if (userinput2.equals(answer2)) {
    count++;
}
if (userinput3.equals(answer3)) {
    count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Comments