[英]can i compare using .equal() for two or more things in the same time
我应该定义四个布尔变量,如下所示:
用户输入课程代码,然后确定学生(用户)是哪个级别,然后根据级别定义4个布尔变量。
但是我不知道如何为两件事或更多做equal()
。
这是我的代码:
import java.util.*;
public class point8 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// declaring
String CourseCode, Level;
boolean Freshman, Sophomore, Junior, Senior;
// input
System.out.println("Course code:");
CourseCode = input.next().toUpperCase();
System.out.println("\nCourse Code: " + CourseCode);
// output
Level = CourseCode.substring(CourseCode.length() - 1);
System.out.println("Student Level: " + Level);
Freshman = Level.equals("1");
System.out.println("Freshman: " + Freshman);
Sophomore = Level.equals("3");
System.out.println("Sophomore: " + Sophomore);
Junior = Level.equals("6");
System.out.println("Junior: " + Junior);
Senior = Level.equals("9");
System.out.println("Senior: " + Senior);
}
}
对于大一新生,我应该怎么做才能从1或2级进行比较,而对于大二学生则要从3级与5级进行比较?
在我看来,最好使用整数,只需将String
解析为int
。
例如:
int myLevel = Integer.parseInt(Level);
if(myLevel >= 3 && myLevel <= 5)
{
System.out.println("Sophomore: " + Sophomore);
}
如果用户插入字母而不是数字,则可能会出错,为避免这种情况,您需要捕获异常并进行处理。 但是,这是一个完全不同的故事,但是您应该阅读以下内容: https ://docs.oracle.com/javase/tutorial/essential/exceptions/
if(Level.equals("9") || Level.equals("10"))
{
//Senior
}
更新:OR运算符是您在前几周应学习的内容。 唯一更基本的方法是只写出第二条if语句。
if(Level.equals("9"))
{
//Senior
}
else if(Level.equals("10"))
{
//Senior
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.