简体   繁体   English

Java isLetterOrDigit() 方法、isDigit()、isLetter()

[英]Java isLetterOrDigit() method, isDigit(), isLetter()

I am trying to figure out how to check a String to validate whether it had at least one letter and one number in it.我想弄清楚如何检查String以验证它是否至少包含一个字母和一个数字。 I will be upfront that this is homework and I am a little confused.我会提前说这是作业,我有点困惑。

There is a method isLetterOrDigit() method that seems it would be the right approach, but I am undure as how I would implement this in my code.有一种方法isLetterOrDigit()方法似乎是正确的方法,但我不确定如何在我的代码中实现它。 Here is the code I am using below:这是我在下面使用的代码:

import javax.swing.JOptionPane;

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

    String initialPassword;
    String secondaryPassword;
    int initialLength;

    initialPassword = JOptionPane.showInputDialog(null, "Enter Your Passowrd.");

    initialLength = initialPassword.length();

    JOptionPane.showMessageDialog(null, "initialLength = " + initialLength);

    while (initialLength < 6 || initialLength > 10)
    {
        initialPassword = JOptionPane.showInputDialog(null, "Your password does not meet the length requirements. It must be at least 6 characters long but no longer than 10.");
        initialLength = initialPassword.length();
    }

    //Needs to contain at least one letter and one digit

    secondaryPassword = JOptionPane.showInputDialog(null, "Please enter your password again to verify.");

    JOptionPane.showMessageDialog(null, "Initial password : " + initialPassword + "\nSecondar Password : " + secondaryPassword);

    while (!secondaryPassword.equals(initialPassword))
    {
        secondaryPassword = JOptionPane.showInputDialog(null, "Your passwords do not match. Please enter you password again."); 
    }

    JOptionPane.showMessageDialog(null, "The program has successfully completed."); 

    }
}

I want to implement a method where the comment section is using either the isDigit() , isLetter() , or isLetterOrDigit() methods, but I just don't know how to do it.我想实现一种方法,其中评论部分使用isDigit()isLetter()isLetterOrDigit()方法,但我不知道该怎么做。

Any guidance would be appreciated.任何指导将不胜感激。 Thanks in advance for the assistance.在此先感谢您的帮助。

This should work.这应该有效。

public boolean containsBothNumbersAndLetters(String password) {
  boolean digitFound = false;
  boolean letterFound = false;
  for (char ch : password.toCharArray()) {
    if (Character.isDigit(ch)) {
      digitFound = true;
    }
    if (Character.isLetter(ch)) {
      letterFound = true;
    }
    if (digitFound && letterFound) {
      // as soon as we got both a digit and a letter return true
      return true;
    }
  }
  // if not true after passing through the entire string, return false
  return false;
}

This seems to be old question and was answered earlier, but I am adding my code as I faced an issue with Thai accented characters.这似乎是个老问题,之前已经回答过,但我正在添加我的代码,因为我遇到了泰语重音字符的问题。 So I worked on to fix that issue and I found the above solution, which was incomplete if you are dealing with such characters - ก่อนที่สุด ท้ายo所以我努力解决这个问题,我找到了上面的解决方案,如果你正在处理这样的角色,这是不完整的 - ก่อนที่สุด ท้ายo

In order to identify these characters correctly here is the code:为了正确识别这些字符,这里是代码:

String value = "abc123ก่อนที่สุด ท้ายo";
    // Loop through characters in this String.
    for (int i = 0; i < value.length(); i++) {
        char c = value.charAt(i);

        // See if the character is a letter or not.
        if (Character.isLetter(c)) {
        System.out.println("This " + c + " = LETTER");
        } 
        if (Character.isDigit(c)) {
        System.out.println("This " + c + " DIGIT");
        }

        if ((""+c).matches("\\p{M}"))
            System.out.println("This " + c + " = UNICODE LETTER");
    }

Not sure if anyone faced this too.不确定是否有人也遇到过这种情况。 Hope this could help.希望这会有所帮助。

You could use the following code:您可以使用以下代码:

import java.util.Scanner;

public class IsDigitisLetter {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        char character;
        System.out.println("Please enter a single character: ");
        character = scnr.next().charAt(0);

        System.out.println(character);

        if (Character.isLetter(character)) {
            System.out.println("The character entered is a letter.");
        } else if (Character.isDigit(character)) {
            System.out.println("The character entered is a digit.");
        }
    }

}
import java.util.*;

public class Main {
  
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        boolean num = false, alpha = false;
        for(int index = 0; index < str.length(); index++){
          if(Character.isAlphabetic(str.charAt(index)))alpha = true;
          else if(Character.isDigit(str.charAt(index)))num = true;
        }
        System.out.print(num & alpha);
    }
}

It's hard to help you do it without giving you all the code to do it, since it's so short.如果不给你所有的代码,很难帮助你做到这一点,因为它太短了。

Anyway for a start, since you need at least one letter and at least one digit, you're going to need two flags, two booleans , which will initially be false .无论如何,首先,由于您至少需要一个字母至少一个数字,因此您将需要两个标志,两个booleans ,它们最初是false You can iterate through each char in ininitialPassword by using a foreach loop:您可以使用foreach循环遍历ininitialPassword的每个char

for (char c : initialPassword.toCharArray())

And then all you have to do is check at each iteration if c is possibly a letter or a digit, and set the corresponding flag if so.然后你所要做的就是在每次迭代时检查c是否可能是一个字母或数字,如果是,则设置相应的标志。 Once the loop terminates, if both the flags are set, then your password is valid.一旦循环终止,如果两个标志都设置了,那么您的密码就有效。 This is what your code could look like:这是您的代码的样子:

boolean bHasLetter = false, bHasDigit = false;
for (char c : initialPassword.toCharArray()) {
   if (Character.isLetter(c))
      bHasLetter = true;
   else if (Character.isDigit(c))
      bHasDigit = true;

   if (bHasLetter && bHasDigit) break; // no point continuing if both found
}

if (bHasLetter && bHasDigit) { /* valid */ }

The code below is the final code that I came up with thanks to your suggestions:下面的代码是我根据您的建议得出的最终代码:

import java.util.Scanner;

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

    String initialPassword;
    String secondaryPassword;
    int numLetterCheck = 0;
    int initialLength;
    boolean digitFound = false; boolean letterFound = false;


    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a new password: ");
    initialPassword = keyboard.nextLine();

    initialLength = initialPassword.length();

    System.out.println("Your initial password length is: " + initialLength);


    while (initialLength < 6 || initialLength > 10)
    {
        System.out.println("Your password does not meet the length requirements of >6 and <10. Please enter a new password.");
        initialPassword = keyboard.nextLine();
        initialLength = initialPassword.length();
    }

    for (char ch : initialPassword.toCharArray())
    {
        if (Character.isDigit(ch))
        {
            digitFound = true;
        }
        if (Character.isLetter(ch))
        {
            letterFound = true;
        }

        if (digitFound && letterFound)
        {
            numLetterCheck = 0;
        }
        else
        {
            numLetterCheck = 1;
        }
    } 

    while (numLetterCheck == 1)
    {
        System.out.println("Your password must contain at least one number and one number. Please enter a new passord that meets this criteria: ");
        initialPassword = keyboard.nextLine();

        for (char ch : initialPassword.toCharArray())
        {
            if (Character.isDigit(ch))
            {
                digitFound = true;
            }
            if (Character.isLetter(ch))
            {
                letterFound = true;
            }

            if (digitFound && letterFound)
            {
                numLetterCheck = 0;
            }
            else
            {
                numLetterCheck = 1;
            }
        }
    }

    System.out.println("Please enter your password again to verify it's accuracy; ");
    secondaryPassword = keyboard.nextLine();

    System.out.println("Initial password : " + initialPassword + "\nSecondar Password : " + secondaryPassword);

   while (!secondaryPassword.equals(initialPassword))
{
    System.out.println("Your passwords do not match. Please enter your password again to verify.");
    secondaryPassword = keyboard.nextLine();    
}

System.out.println("The program has successfully completed.");  

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 isLetter方法在Java中不起作用 - isLetter Method isn't working in Java java 方法 Character.isDigit(char) 返回 true,输入为 'O' - The java method Character.isDigit(char) returns true with an input of 'O' Java:使用isDigit函数 - Java: Using the isDigit function 使用Character.isLetter和Character.isDigit忽略数字,空格和读取字符串输入 - Ignoring digits, blank spaces and read String input, using Character.isLetter & Character.isDigit Character.isLetterOrDigit(char)在java 6和7中返回不同的值 - Character.isLetterOrDigit(char) returns different value in java 6 and 7 Character.isDigit() 错误:找不到适合 isDigit(String) 的方法 - Character.isDigit() error: no suitable method found for isDigit(String) Java 中的 Character.isAlphabetic 和 Character.isLetter 有什么区别? - What is the difference between Character.isAlphabetic and Character.isLetter in Java? 为什么有时当我通过java中的isDigit方法检查字符是否为数字时,出现错误? - Why sometimes when I check whether a character is a digit by method isDigit in java, I get error? 在 function “isDigit” java.lang.ArrayIndexOutOfBoundsException:5 - in function “isDigit” java.lang.ArrayIndexOutOfBoundsException: 5 isDigit方法中的Character.isDigit参数和行不可用错误(说明) - Character.isDigit parameters and line unavailable errors within the isDigit method (clarification)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM