2014-03-29 5 views
2

내 프로그램에 루프를 추가하여 사용자가 잘못된 이름을 입력하면 프로그램의 시작 부분으로 돌아가서 이름을 다시 입력하도록 요청합니다. do-while 루프가 필요하다고 생각하지만 if 문과 부울을 이미 구현 한 방법을 잘 모르겠습니다. 사용자에게 3 개의 항목 만 있고 3 번 잘못 입력하면 프로그램이 종료되기를 바란다.do-while 루프를 사용하여 사용자 입력을 다시 확인하는 방법은 무엇입니까?

import java.util.Scanner; 

public class Username 
{ 
    public static void main(String[] args) 
    { 
    { 
     Scanner kb = new Scanner(System.in); 
     // array containing usernames 
     String[] name = {"barry", "matty", "olly", "joey"}; // elements in array 


     System.out.println("Enter your name"); 
     String name1 = kb.nextLine(); 
     boolean b = true; 
     for (int i = 0; i < name.length; i++) 
     { 
     if (name[i].equals(name1)) 
     { 
      System.out.println("you are verified you may use the lift"); 
      b = false; 
      break;// to stop loop checking names 
     } 
     } 

     if (b) 
     { 
     System.out.println("Invalid entry 2 attempts remaining, try again"); 
     } 
    } 
+1

몇 분 전에 질문을했습니다. 나는 당신에게 답을 주었고, 지금 당신은 여기에 제 코드를 붙여 넣었고 당신은 다시 묻고 있습니다 ... – ruhungry

+0

그리고 답을 받아 들일 필요가 있습니다. – Salah

+1

@Salah 또는 어쩌면 우리는 대답을하지 말아야합니다.) – ruhungry

답변

1

while 루프에서 조건을 사용할 수 있습니다.

boolean b = false; 
while(!b){ 
    System.out.println("Enter your name"); 
    String name1 = kb.nextLine(); 
    for (int i = 0; i < name.length; i++) { 
     if (name[i].equals(name1)) { 
      b = true; 
      System.out.println("you are verified you may use the lift"); 
     }else{ 
      System.out.println("Invalid entry 2 attempts remaining, try again"); 
     } 
    } 
} 

이름 조건이 충족되면 루프가 종료되고 그렇지 않으면 루프가 종료됩니다.

1

당신은 이런 식으로 작업을 수행 할 수 있습니다

int count = 0; 
point: 
do { 
    System.out.println("Enter your name"); 
    String name1 = kb.nextLine(); 
    boolean b = true; 
    for (int i = 0; i < name.length; i++) { 
     if (name[i].equals(name1)) { 

      System.out.println("you are verified you may use the lift"); 
      b = false; 
      break point;// to stop loop checking names 
     } 
    } 

    if (b) { 
     count++; 
     System.out.println("Invalid entry 2 attempts remaining, try again"); 
    } 
while(!b || count <=3) 
1
package com.loknath.lab; 

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Scanner; 

public class User1 { 
public static void main(String[] args) { 

    Scanner kb = new Scanner(System.in); 
    // array containing usernames 
    String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements 
    String []temp=name; 
    Arrays.sort(temp); 
    while (true) { 

     System.out.println("Enter your name"); 
     String name1 = kb.nextLine(); 

     if (Arrays.binarySearch(temp,name1)>=0) { 
      System.out.println("you are verified you may use the lift"); 
      break; 
     } else { 
      System.out.println("Not a verified user try again!"); 
     } 

    } 
    System.out.println("Done"); 
} 

} 

출력

Enter your name 
    loknath 
    Not a verified user try again! 
    Enter your name 
    chiku 
    Not a verified user try again! 
    Enter your name 
    zerr 
    you are verified you may use the lift 
    Done 
+0

예. 그것의 작동 .. – user3386829

+0

'binary'는'name' 배열의 요소가 정렬 될 때에 만 작동합니다. 그러한 제약이 없다는 질문에 –

+0

배열 안에 요소가 있으면 그 값을 + ve 값으로 반환합니다. 그렇지 않으면 -ve를 반환합니다. – loknath

1

사용하여 다음과 같은 접근 방식. 좋은 점은 그것이 깨끗하고 강력한 솔루션이라는 것입니다.

import java.util.Arrays; 
import java.util.List; 
import java.util.Scanner; 

public class AccessPoint 
{ 
    private Scanner scanner; 
    private List<String> usernames; 

    public AccessPoint() 
    { 
    scanner = new Scanner(System.in); 
    usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey"); 

    if (tryAccessForTimes(3)) 
    { 
     allowAccess(); 
    } 
    else 
    { 
     denyAccess(); 
    } 

    scanner.close(); 
    } 

    public static void main(String[] args) 
    { 
    new AccessPoint(); 
    } 

    private boolean tryAccessForTimes(int times) 
    { 
    boolean accessAllowed = false; 

    for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++) 
    { 
     String userInput = getUserName(); 

     for (String userName : usernames) 
     { 
     if (userName.equals(userInput)) 
     { 
      accessAllowed = true; 
      break; 
     } 
     } 

     if (!accessAllowed) 
     { 
     printNumberOfTriesLeft(times, tryIndex); 
     } 
    } 

    return accessAllowed; 
    } 

    private void printNumberOfTriesLeft(int times, int tryIndex) 
    { 
    int triesLeft = times - tryIndex; 

    if (triesLeft != 0) 
    { 
     System.out.println("You have " + triesLeft 
     + (triesLeft == 1 ? " try" : " tries") + " left."); 
    } 
    } 

    private String getUserName() 
    { 
    System.out.print("Enter Username: "); 
    return scanner.nextLine(); 
    } 

    private void allowAccess() 
    { 
    System.out.println("Access Granted. Allowed to use lift."); 
    } 

    private void denyAccess() 
    { 
    System.out.println("Access Denied."); 
    } 
} 
관련 문제