[英]reading in a string and printing a char
I am supposed to read in a string, convert it to lowercase, then return the first character in the string.我应该读入一个字符串,将其转换为小写,然后返回字符串中的第一个字符。 If the first character is not a string I'm supposed to print \0
.如果第一个字符不是字符串,我应该打印\0
。
I have tried:我努力了:
String ch = sc.nextLine();
char c = ch.charAt(0);
if (Character.isLetter(c)) {
ch = ch.toLowerCase();
c = ch.charAt(0);
return c;
}
return '\0';
You need to change char
variables to String
variables with String.valueOf(c)
before you return them.您需要在返回之前使用String.valueOf(c)
将char
变量更改为String
变量。
String ch = sc.nextLine();
char c = ch.charAt(0);
if (Character.isLetter(c)) {
ch = ch.toLowerCase();
c = ch.charAt(0);
return String.valueOf(c);
}
return String.valueOf('\0');
}
That exception means that your scanner didn't find anything to return from its' source.该异常意味着您的扫描仪没有找到任何可以从其源返回的内容。 Strings in java are not like C strings where they have at least one character ('\0'). java 中的字符串不像 C 字符串那样至少有一个字符 ('\0')。 You can protect the program from failing with the following addition:您可以通过以下添加来保护程序免于失败:
try
{
String ch = sc.nextLine();
ch = ch.toLowerCase();
char c = ch.charAt(0);
if (Character.isLetter(c))
{
return c;
}
return '\0';
}
catch(StringIndexOutOfBoundsException ex)
{
System.out.println("You have entered an empty string");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.