[英]How can I modify my code to only accept a certain data type?
What can I do to modify this, is there any java function for that?我该怎么做才能修改它,是否有任何 java 函数? What needs to be done so that it only accepts characters and returns an error message for other data types?
需要做什么才能使其只接受字符并返回其他数据类型的错误消息?
import java.util.*;
public class problem5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter from the alphabet: ");
char letter = in.next(".").charAt(0);
char vowels[] = {'A','E','I','O','U','a','e','i','o','u'};
int vowelcount = 0;
for (int i = 0; i < 10; i++)
{
if (vowels[i] == letter)
{
vowelcount++;
}
}
if (vowelcount > 0)
{
System.out.println("You entered a vowel.");
}
else
{
System.out.println("You entered a consonant.");
}
}
}
I need to reject input that has more than 1 char – Nico Dela Cruz
我需要拒绝超过 1 个字符的输入 – Nico Dela Cruz
You just need to check the length of your input您只需要检查输入的长度
String input = in.next(".");
if(input.length == 1){
char letter = input.charAt(0);
...
}
Add an else
if you want to add an error message of some sort.如果要添加某种错误消息,请添加
else
。
To check the input to only accept letter
, you have Character.isLetter(char)
to check every "letter" in UNICODE for you.要检查仅接受
letter
的输入,您可以使用Character.isLetter(char)
来检查 UNICODE 中的每个“字母”。
If you want to only accept a range of az
and/or AZ
, you can do it yourself with an if condition or using regex.如果您只想接受
az
和/或AZ
的范围,您可以使用 if 条件或使用正则表达式自行完成。
Wrap your loop in a statement such as:将循环包裹在如下语句中:
if (Character.isLetter(letter)){
and put and else
clause at the end for your error并在最后放置和
else
子句以解决您的错误
Edit:编辑:
OP has changed their question slightly, so you can either: OP 稍微改变了他们的问题,因此您可以:
-Accept only the first character entered: - 只接受输入的第一个字符:
char letter = in.next().trim().charAt(0);
-Or as AxelH said above, only proceed if user enters one char: - 或者如 AxelH 上面所说,只有在用户输入一个字符时才继续:
if(input.length == 1){
char letter = input.charAt(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.