需求:驗證用戶名和密碼是否正確,如果不正確分別給出提示。
假設用戶名爲 lily,密碼爲 gotit,代碼如下:
import java.util.Scanner;
public class Login {
public static void main(String args[]){
System.out.println("Please input your username: ");
Scanner scan = new Scanner(System.in);
String user = scan.nextLine();
System.out.println("Please input your password: ");
String pwd = scan.nextLine();
if(!user.equals("lily")){
System.out.println("The username is invalid, please input again!");
}else if(!pwd.equals("gotit")){
System.out.println("The password is invalid, please input again!");
}else
System.out.println("Congratulation! You've login!");
}
}
關鍵知識點:
1. Scanner 類的 nextLine() 方法和 next() 方法
next():
- 以空格爲結束符,一定要讀取到有效字符後纔可以結束輸入
- 對輸入有效字符之前遇到的空白,next() 方法會自動將其去掉
- 只有輸入有效字符後纔將其後面輸入的空白作爲分隔符或者結束符
- 不能得到帶有空格的字符串
nextLine():
- 以 Enter 爲結束符,也就是說它返回的是輸入回車之前的所有字符
- 可以得到帶有空格的字符串
2. equals() 方法
- 字符串是引用類型的對象,必須用 equals() 方法比較兩個字符串的內容是否相等
- == 是用於比較基本數據類型是否相等,及引用類型的地址是否相等