gpt4 book ai didi

java - 有没有更好的方法来编写与我相同的代码?

转载 作者:行者123 更新时间:2023-11-29 07:24:06 24 4
gpt4 key购买 nike

我想将此代码编写为排除数字和符号或符号的元音查找器,除了将它们一一添加之外还有更好的方法吗?代码工作正常,但我认为有更好的方法来做到这一点。我是 Java 的新手,两周前刚学过。

import java.util.Scanner;
public class ConsonantOrVowel {
public static void main(String[] args) {
char c;
System.out.println("Please Input a Character: ");
Scanner input = new Scanner(System.in);
c=input.next().charAt(0);
if(c == '1'|| c == '2'|| c == '3'|| c == '4'|| c == '5' ||c == '6' ||c == '7'||c == '8'||c == '9'|| c == '!'|| c == '@' ||c == '#' ||c == '$'||c == '%'||c == '^'|| c == '&'|| c == '*' ||c == '(' ||c == ')'||c == '_'||c == '+'|| c == '-'|| c == '/'||c == '['|| c == ']'|| c == '{' ||c == '}' ||c == ';'||c == ':'||c == '"'|| c == ','|| c == '.'|| c == '?'){
System.out.println("Invalid Input");
}
else if(c == 'A'|| c == 'a'|| c == 'E' ||c == 'e' ||c == 'I'||c == 'i'||c == 'O'||c == 'o'||c == 'U'||c == 'u') {
System.out.println("Input Character is a Vowel");
}
else
System.out.println("Input Character is a Consonant");
}
}

最佳答案

你可以使用 String.inxedOf(char c):

public class ConsonantOrVowel {
public static void main(String[] args) {
char c;
System.out.println("Please Input a Character: ");
Scanner input = new Scanner(System.in);
c = input.next().charAt(0);

if ("123456789!@#$%^&*()_+-/[]{};:\",.?".indexOf(c) > -1) {
System.out.println("Invalid Input");
} else if ("AaEeIiOoUu".indexOf(c) > -1) {
System.out.println("Input Character is a Vowel");
} else
System.out.println("Input Character is a Consonant");
}
}

关于java - 有没有更好的方法来编写与我相同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com