[英]Read multiple characters in char input and convert to double
public static void main(String[] args)
{
char ch;
ch = JOptionPane.showInputDialog("").charAt(0);
if (Character.isLetter(ch))
{
System.out.println(Character.toUpperCase(ch));
}
if (Character.isDigit(ch))
{
Math.sqrt(ch);
System.out.println(ch);
}
if (Character.isWhitespace(ch))
{
int code = ch;
System.out.println (code);
}
}
If I input more than one character, it only recognises the first character. 如果输入多个字符,则只能识别第一个字符。 How do I make the program see multiple characters that a user inputs as a char? 如何使程序看到用户输入为字符的多个字符?
You are taking only the first character
with this:- 您只使用第一个character
:-
ch = JOptionPane.showInputDialog("").charAt(0);
The charAt(0)
gives you the character
with the index of 0
, which is always the first character. charAt(0)
为您提供索引为0
的character
,该character
始终是第一个字符。
If you want to treat your input
as a Whole and not only the First character, try using a String as follows 如果要将input
而不是第一个字符视为一个整体,请尝试按以下方式使用字符串
String s = JOptionPane.showInputDialog("");
Also note that your Charater.isLetter(ch)
won't work now, as you can't do that with a String
. 另请注意,您的Charater.isLetter(ch)
现在将无法使用,因为您无法使用String
来做到这一点。 However, you can convert the whole String
to UpperCase
if you want. 但是,您可以根据需要将整个String
转换为UpperCase
。 Also, you can't easily look whether String
is a valid Double
or not. 另外,您不能轻易查看String
是否为有效的Double
。 It requires exception handling
and may be confusing. 它需要exception handling
并且可能会造成混淆。 I am including it anyway, so if you are confused,feel free to ask. 无论如何我都会把它包括在内,所以如果您感到困惑,请随时提出。
The Final Program looks like this:- 最终程序如下所示:
String s;
s = JOptionPane.showInputDialog("");
try{
double d = Double.parseDouble(s);
}catch(Exception e){
//Not a Double as it comes inside catch
//Therefore String must be empty or contain Characters
//Checking for Empty
if(s.trim().length()<1){
//String is empty
//Do what you want
System.out.println("String is whitespace");
}else {
//String must contain Characters.
System.out.println(s.toUpperCase());
}
}
Please ask, if you are stuck at anything. 请问,如果您遇到任何困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.