2013-11-09 16 views
-4

」有沒有辦法讓一個「如果」在另一個「如果」如果使用戶名不正確,它不要求密碼,但立即說用戶名不正確?如果「

import java.util.Scanner; 
public class SecurityPasscode 
{ 
    public static void main(String[] args) 
    { 
     Scanner user_input = new Scanner(System. in); 
     System.out.println("Enter Username"); 

     String username; 
     username = user_input.next(); 

     if (username.equals("username")) 
      System.out.println("Enter Password"); 

     String password; 
     password = user_input.next(); 

     if (password.equals("password")) 
      System.out.println("Welcome back " + username + "!"); 

     if (!"password".equals(password)) 
      System.out.println("That password is incorrect."); 
     else if (!"username".equals(username)) 
      System.out.println("That username is incorrect."); 

    } 
} 

回答

3

後你的第一個if ....

注意代碼這兩個塊一樣添加{

if(something1) 
    command1; 
    command2; 
    if(something2) 
    command3; 
else if(something3) 

if(something1) { 
    command1; 
    command2; 
    if(something2) 
    command3; 
} 
else if(something3) 

在第一代碼,所述else對應於最後如果。在第二個代碼中,它對應於第一個if。此外,在第一個代碼,command2是不是在外部if的範圍,因爲Java沒有真正關心縮進..

0
if (condition) 
{ 
    if (another condition) 
    { 
     // statements here 
    } 
} 
1
if (username.equals("username")){ 
    System.out.println("Enter Password"); 
}else{ 
    String password; 
    password = user_input.next(); 
    if (password.equals("password")){ 
     System.out.println("Welcome back " + username + "!"); 
    }else{ 
     System.out.println("That password is incorrect."); 
    } 
} 
0

是...

if(eval) 
    if(anotherEval) 
     .... 
      code 

你可以有任何數量的嵌套,如果你喜歡:)