Создание метода для проверки идентификатора пользователя - PullRequest
1 голос
/ 06 мая 2019

Я пытаюсь написать код Java (метод) для проверки идентификатора пользователя. который предлагает пользователю ввести идентификатор. Если пользователь начинает с цифры 1 - это будет отображаться как недействительный !!! Буду благодарен за любую помощь! Спасибо

public static void main(String[] args) {
    //creating an array of 10   
    int[] num = new int[10];

    //asking user to enter a number        
    Scanner kb = new Scanner(System.in);
    System.out.println("Enter and id number : ");
    num = kb.nextInt();

    //calling method    
    GetValidInteger(num);
}
//method
static void GetValidInteger(int[] num) {
    //looping through the array to get the numbers
    for (int i = 0; i < num.length; i++) {
        //if num at index 0 is 1 print out invalid
        if (num[0] == 1) {
            System.out.println("The number you have entered :" + num + "  starts with 1 and is invalid");
        }

        //else print out valid
        else {
            System.out.println("The number you have entered :" + num + " is valid");
        }
    }
}

Я получаю сообщение об ошибке: int cannot be converted into int[]! по этой строке: num = kb.nextInt();

Ответы [ 2 ]

1 голос
/ 06 мая 2019

Вы передаете int, а не int[] методу GetValidInteger.

Измените его следующим образом:

// Renamed with a starting lower case because a starting uppercase char is used
// normally for class and interface names.
public static void getValidInteger(int num) {
   // Consider the string representation of that num
   String str = String.valueOf(num);

   // Get the first character of the string version of the int num
   if (str.charAt(0) == '1') {
       System.out.println("The number you have entered :" + num
                          + "  starts with 1 and is invalid");
   } else {
       System.out.println("The number you have entered :" + num + " is valid");
   }
} 
0 голосов
/ 06 мая 2019

Вы присваиваете int массиву int.Вот почему у вас есть ошибка.Я не понимаю, почему вы используете массив.Используйте цикл, пользователю будет предложено ввести идентификатор, пока он не будет правильным.

public class Test
{

public static void main(String[] args)
{
    int currentId;

    while (true)
    {
        //asking user to enter a number
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter and id number : ");
        currentId = kb.nextInt();

        //calling method
        if (GetValidInteger(currentId))
        {
            //If the id is valid, you re out from the loop, if not retry
            break;
        }
    }

}

//method
static boolean GetValidInteger(int currentId)
{
    boolean isValidId = false;
    boolean doesIdStartWith1 = String.valueOf(currentId).startsWith("1");
    //if num at index 0 is 1 print out invalid
    if (doesIdStartWith1)
    {
        System.out.println("The number you have entered :" + currentId + "  starts with 1 and is invalid");
    }
    else
    {
        //else print out valid

        System.out.println("The number you have entered :" + currentId + " is valid");
        isValidId = true;
    }
    return isValidId;
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...