2015-01-31 2 views
0

나는 AS 수준의 컴퓨팅 클래스에서 Java를 배우기 시작했으며, 실제로 설정 한 첫 번째 DIY 작업을 수행했습니다.do-while 루프 다음에 코드가 계속되지 않습니까?

do-while 문을 사용하여 사용자의 입력 사용자 이름이 배열 "names"에 있는지 확인했습니다. 그렇지 않은 경우 올바른 사용자 이름이 입력 될 때까지 사용자 이름을 다시 입력해야합니다. 나는 또한 부울을 설정 했으므로 올바른 사용자 이름을 입력하면 do-while 루프가 취소되고 코드가 계속됩니다.하지만 그렇지 않습니다.

String[] names = {"mckeownl", "heardj", "williamsc"}; 
String[] attendance = {"yes", "no", "yes"}; 
int[] grade = {96, 66, 73}; 

boolean loggedin = false; 

Scanner user_input = new Scanner(System.in); 
String login; 
login = user_input.next(); 

do { // beginning of while - login 

    System.out.println("Insert student's surname followed by the first letter"); 
    System.out.print("of their first name (e.g John Smith = smithj): "); 

    if (Arrays.asList(names).contains(login)) { 
     System.out.println("Student selected: "+login+"."); 
     loggedin = true; 
    } 
    else { 
     System.out.println("Incorrect student name! Please try again."); 
     loggedin = false; 
    } 

} while (! loggedin); 

if (login.equals(names[0])) { 
    System.out.println("Attend today: "+attendance[0]); 
    System.out.println("Grade: "); 
} 
else { 
    System.out.println("poo"); 
} 

    } 
} 

올바른 이름의 출력은 다음과 같습니다.

"성씨의 첫 글자 (예 : John Smith = smithj) 다음에 학생의 성을 입력하십시오. mckeownl 학생 선택 : mckeownl."

최종 if 문이 출력되지 않는 이유는 무엇입니까?

+1

루프 외부에서'login'을 요청하는 이유는 무엇입니까? –

+0

코드에 대한 한 가지 문제점은 ","가 유효한 로그인이 아니어야한다는 것입니다. 또한 "". –

답변

0

루프 내부에서 로그인을 요청해야합니다.

오류가 발생하면 loggedin 변수를 false로 설정하면 안됩니다. 실패한 텍스트 만 입력하면 맨 위로 돌아가서 다시 로그인 할 것입니다.

메서드 호출시 여러 줄을 사용할 수 있습니다. 그래서 당신은 할 수 : 대신

System.out.println("Insert student's surname followed by the first letter " + 
"of their first name (e.g John Smith = smithj): "); 

:

System.out.println("Insert student's surname followed by the first letter"); 
System.out.print("of their first name (e.g John Smith = smithj): "); 
0

다시 loggedin에 대한 사용자 위해서는 .. 루프 내부에 login = user_input.next();을 넣어 .. 업데이트

do { // beginning of while - login 

System.out.println("Insert student's surname followed by the first letter"); 
System.out.print("of their first name (e.g John Smith = smithj): ") 

login = user_input.next(); // <--- you should ask for login here 
... 

을 :

//for the final if statement 
if (loggedin) { //just use this boolean variable since you used it as an indicator if it is valid name or not 
    System.out.println("Attend today: "+attendance[0]); 
    System.out.println("Grade: "); 
} 
else { 
    System.out.println("poo"); 
} 

실제로 루프 내부에서 조건을 넣을 필요가 없습니다. 따라서 이름이 유효하지 않은 경우 사용자가 유효한 이름을 입력 할 때까지 루프를 종료하지 않습니다. 그것은 루프 이후에 이것을 좋아한다.

do{ 
.. 
}while(..) 

System.out.println("Attend today: "+attendance[0]); 
System.out.println("Grade: "); 
+0

나는 이것을했지만, 여전히 내 문제를 해결하지 못한다.루프 외부에있는 나의 마지막 if 문은 여전히 ​​실행되지 않습니다. – LuketheWillyman

+0

최종 조건은''mckeownl ''인 배열의 첫 번째 요소 만 비교합니다. 그래서 배열'name'의 모든 원소와 비교하기 위해서 루프가 필요하거나 부울'loggedin'을 사용해야합니다. 배열에 이름이 존재하면 지시자로 사용하기 때문에 –

+0

흠, 제가 바꿨습니다. 마지막으로 첫 번째 경우 (로그인했는지 여부를 확인) 작동하지 않았고 두 번째 것으로 변경되었지만 여전히 작동하지 않았습니다. 해결책을 찾으려고 아직도 노력하고 있습니다. – LuketheWillyman

0

내가 처음부터 시작했고, 같은 원칙을 사용하지만 내 대답을 해결했다.

각자 고유 한 로그인, 비밀번호 생성 및 비밀번호 입력을하는 세 명의 사용자가 있습니다 (더 나은 방법이 있다면 말하십시오).

package codeyom9a; 

import java.util.Scanner; 
public class Codeyom9a { 

public static void main(String[] args) { 

String[] names = {"Luke", "Jack", "Brad" }; 
String[] surnames = {"Mckeown", "Heard", "Reed" }; 


Scanner user_input = new Scanner(System.in); 

boolean firstloggedin; 
boolean passloggedin; 



String firstlogin; 

do {                  //login first name 
    firstloggedin = false; 
    System.out.print("Enter your first name: "); 
    firstlogin = user_input.next(); 

    if (firstlogin.equals(names[0]) || firstlogin.equals(names[1]) || firstlogin.equals(names[2])) { 
     firstloggedin = true; 

    } 
    else { 
     System.out.println("Please try again."); 
    } 

} while (! firstloggedin); 

boolean secondloggedin; 


String secondlogin; 

do {                  //login surname 
    secondloggedin = false; 
    System.out.print("Enter your surname: "); 
    secondlogin = user_input.next(); 

    if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])|| secondlogin.equals(surnames[1]) & firstlogin.equals(names[1]) || secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) { 
     secondloggedin = true; 

    } 
    else { 
     System.out.println("Please try again."); 
    } 

} while (! secondloggedin); 

if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])) {  //pass login user 1 

    String password1;              //pass create user 1 
    System.out.print("Create a password (no spaces): "); 
    password1 = user_input.next(); 

    boolean passloggedin1 = false; 

    do{ 

     String passwordenter1;            //pass enter user 1 
    System.out.print("Enter your password now: "); 
    passwordenter1 = user_input.next(); 

    if (passwordenter1.equals(password1)) { 
     passloggedin1 = true; 
     System.out.println("Correct! You have now logged in."); 
    } 
    else { 
     System.out.println("Incorrect password!"); 
    } 
    } while (! passloggedin1); 


}                   //end user 1 


if (secondlogin.equals(surnames[1]) & firstlogin.equals(names[1])) {  //pass login user 2 

    String password2;              //pass create user 2 
    System.out.print("Create a password (no spaces): "); 
    password2 = user_input.next(); 

    boolean passloggedin2 = false; 

    do{ 

     String passwordenter2;            //pass enter user 2 
    System.out.print("Enter your password now: "); 
    passwordenter2 = user_input.next(); 

    if (passwordenter2.equals(password2)) { 
     passloggedin2 = true; 
     System.out.println("Correct! You have now logged in."); 
    } 
    else { 
     System.out.println("Incorrect password!"); 
    } 
    } while (! passloggedin2); 


}                   //end user 2 

if (secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) {  //pass login user 3 

    String password3;              //pass create user 3 
    System.out.print("Create a password (no spaces): "); 
    password3 = user_input.next(); 

    boolean passloggedin3 = false; 

    do{ 

     String passwordenter3;            //pass enter user 3 
    System.out.print("Enter your password now: "); 
    passwordenter3 = user_input.next(); 

    if (passwordenter3.equals(password3)) { 
     passloggedin3 = true; 
     System.out.println("Correct! You have now logged in."); 
    } 
    else { 
     System.out.println("Incorrect password!"); 
    } 
    } while (! passloggedin3); 


}                   //end user 3 

    } 
} 

는 "누가 복음", "잭"또는 "브래드"를 입력하면, 그 다음합니다 ('성씨'배열에 같은 인덱스에있는) 성을 위해 요청합니다. 둘 다 맞으면 암호 생성을 요청한 다음 사용자가 생성 된 암호를 입력하도록 요청합니다.

내 첫 번째 코드와 관련하여 왜 이것이 작동하는지, 다른 이유는 무엇인지, 왜 그런지 모릅니다.

관련 문제