2011-08-25 85 views
-2

我需要检查一个字符串是否实际上是一个字符(仅由1个字符组成)。如何判断一个String是否真的是Java中的一个字符?

这是我到目前为止。

Scanner keyboard = new Scanner(System.in); 
String str = keyboard.next(); 
    if (isChar(str = a) == true) 
    { 
     System.out.print("is a character"); 
    } 
+0

谢谢我无法让格式化完成尝试。 – ppja

+0

'isChar(str = a)== true' !!! Java不需要'== true'。 –

+0

这个问题还不清楚。 –

回答

0

A(非空)的字符串可以是零个或多个字符。所以,你想不喜欢的东西:

String str = ...; 
if (str != null && str.length() > 0) { 
    if (str.charAt(0) == 'a') { 
    ... 
    } 
} 

在你的问题,目前还不清楚到底是什么“isChar”是的,但你上面写的代码似乎并没有语义正确。

0

看一看的Javadoc String

boolean isChar(String target,String check) { 
    if (target != null && check != null){ 
     return target.indexOf(check) > -1; 
    } else { 
     return false; 
    } 
} 
0

您可以使用String.contains(CharSequence)

package so7185276; 

import java.util.Scanner; 

public final class App { 
    /** 
    * Check if provided {@link String} contains specified substring 
    * (case-sensitive). Print out "{str} contains {what}" if so. 
    * 
    * @param str 
    *   {@link String} to look into 
    * @param what 
    *   {@link String} to look for 
    */ 
    private static void isChar(final String str, final String what) { 
     if (str != null && what != null && str.contains(what)) { 
      System.out.println(str + " contains " + what); // NOPMD (sysout is used) 
     } 
    } 

    public static void main(final String[] args) { 
     final Scanner keyboard = new Scanner(System.in); 
     final String str = keyboard.next(); 
     isChar(str, "A"); 
     isChar(str, "B"); 
     isChar(str, "C"); 
    } 

    /** 
    * Constructor. 
    */ 
    private App() { 
     // avoid instantiation 
    } 
} 
0

我不能确定你想要什么,但这些选项之一可能为你工作:

String str = keyboard.next(); 

// If you want to check that the input contains "a" 
if (str.contains("a")) { 
    System.out.print("a"); 
} 

// If you want to check that the whole input is "a" 
if (str.equals("a")) { 
    System.out.print("a"); 
} 

如果你知道的输入是一个聊天,可以考虑使用Scanner.nextByte()

相关问题