How to use do-while loop to check user input again?

我的梦境 提交于 2019-12-10 23:29:01

问题


I want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.

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:


You can use a condition in the while loop. Something along the lines of:

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");
        }
    }
}

The loop will quit if the name condition is fulfilled and will loop around if it is not.




回答2:


You can do it like this:

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)



回答3:


Use the following approach. Good thing is that it is a clean and robust solution.

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.");
  }
}



回答4:


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");
}

 }

output

  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


来源:https://stackoverflow.com/questions/22733632/how-to-use-do-while-loop-to-check-user-input-again

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!