如何使用do-while循环再次检查用户输入? [英] How to use do-while loop to check user input again?

查看:84
本文介绍了如何使用do-while循环再次检查用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在程序中添加一个循环,以便当用户输入错误的名称时,它返回到程序的开头,并要求他们再次输入其名称。我想我需要一个 do-while 循环,但是我不确定如何使用if语句和已经包含的布尔值来实现它。我希望用户只有三个条目,如果他们输入错误三遍,则程序将关闭。

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


推荐答案

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

这篇关于如何使用do-while循环再次检查用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆