如何创建具有3个条件的if语句? (JAVA)

时间:2016-09-10 04:48:44

标签: java if-statement

我刚开始学习java一周前。我在学校上课。我正在尝试创建一个测验,但我无法弄清楚如何打印出分数。测验有三种可能性:3 / 3,2 / 3,1 / 3。我遇到的问题是在程序结束时附近的if语句。

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.");
       }   

     }

}

2 个答案:

答案 0 :(得分:1)

此,

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

应该是

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

我更喜欢count。以及一个显示不同消息的数组。像

这样的东西
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]);

答案 1 :(得分:-1)

只需在if类中的每个条件之前添加大括号,否则添加

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.");
}