gpt4 book ai didi

java - 如何创建包含 3 个条件的 if 语句? ( java )

转载 作者:行者123 更新时间:2023-12-01 06:08:38 25 4
gpt4 key购买 nike

我一周前才开始学习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.");
}

}

}

最佳答案

这个,

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))) {

但是我更喜欢计数。以及一个显示不同消息的数组。类似的东西

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]);

关于java - 如何创建包含 3 个条件的 if 语句? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com