[英]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.