2011-08-25 62 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()

相關問題