【问题标题】:How would I put limits to the char's length?我将如何限制字符的长度?
【发布时间】:2021-07-23 03:55:44
【问题描述】:

问题是:编写一个 Java 程序,要求用户提供字母表中的单个字符。根据用户输入打印元音或辅音。如果用户输入不是字母(在 a 和 z 或 A 和 Z 之间),或者是长度 > 1 的字符串,则打印适当的描述性错误消息。

我做了一个 switch 语句,成功地告诉你是元音还是辅音,但如果用户输入的长度超过一个字符,我不知道如何给出错误消息。

import java.util.Scanner;
public class VowelKL{
public static void main(String[] args){

int i=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
char letter=input.next().charAt(0);

switch(letter)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' : 
case 'A' :
case 'E' :
case 'I' : 
case 'O' :
case 'U' : i++;
}
if(i==1)
System.out.println("You entered the letter " + letter + " and it is a Vowel!");
else
if((letter>='a' && letter<='z')||(letter>='A' && letter<='Z'))
System.out.println("You entered the letter " + letter + " and it is a Consonant!");
else
System.out.println("You did not enter a single character from the alphabet, please try again.");



}
}

【问题讨论】:

    标签: java char switch-statement


    【解决方案1】:

    正如您已经在用户输入命令中指定的那样,用户输入仅允许在索引 0 处,即 charAt(0)。所以没有其他方法可以提取该字符值的索引位置。除非您必须在字符串类型中转换该特定字符,然后您才能访问字符串的

    str.lastIndexOf(char) 方法提供限制。 这不是最佳做法。

    【讨论】:

    • 不是很有用的答案。
    • @blagerweij,你能提出更好的建议吗?
    • 问题的问题是用户输入立即存储在单个字符中:char letter=input.next().charAt(0);。将 char 转换为 String 并不能解决该问题,将 input.next() 的结果存储在 String 中,然后检查该 String 的长度即可解决问题。
    • @blagerweij,感谢它,但他要求限制而不是强制转换和长度验证
    【解决方案2】:

    你可以使用这样的东西

    public int length() {  
          return i.length;  
      } 
    

    有几种方法可以做到这一点,以上只是一个示例,但.length() 属性将为您提供字符串长度的 int 值。在上述情况下,我们将 int 作为值返回。

    在您的情况下,您可以创建一个新的 int 变量,然后为其分配长度。

    int x = letter.length()
    

    这会将字符串的长度转换为 int 值。然后,您可以使用它并编写一个 if 语句来判断它何时高于或低于 1 的值。

    编辑:

    我很快用 java 写了这个,它似乎按预期工作。希望这有助于为您指明正确的方向。请注意,您需要将变量 letterchar 更改为 String

    import java.util.Scanner;
    
    public class main {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input=new Scanner(System.in);
        System.out.println("Enter a single letter from the alphabet: ");
        String letter= input.nextLine();
        
        if (letter.length() == 1)
            System.out.println("Only one letter was entered");
        else
            System.out.println("Either no letter or more than one letter was entered");         
    }
    

    【讨论】:

    • 如何将变量 letterchar 更改为 string
    • 就像我做的那样。我改变了'char letter = input.next().charAt(0);'到“字符串字母= input.nextLine();”。您将无法在 char 上使用 .length() 属性。所以我会改用字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多