2013-02-06 45 views
2

我正嘗試在Java中創建一個基於文本的遊戲,我將要求輸入用戶名並將其插入遊戲中。我試圖用他們輸入的字符串評估任何數字。即09452asdf1234Java,確保用戶不輸入字符串中的數字

下面是與問題相關的代碼。

String name, choiceSelection; 
int choice; 
name = JOptionPane.showInputDialog(null, "Enter your name!"); 

//CHECKS IF USER ENTERED LETTERS ONLY 
if (Pattern.matches("[0-9]+", name)) 
{ 
    throw new NumberFormatException(); 
} 
else if (Pattern.matches("[a-zA-Z]+", name)) 
{ 
    if (Pattern.matches("[0-9]+", name)) 
    { 
     throw new NumberFormatException(); 
    } 
} 

我試圖找出如果任何號碼是在字符串中,如果是,拋出一個NumberFormatException,讓他們知道,他們沒有按照正確的提示。

確保用戶不在name字符串中輸入數字的最佳方法是什麼?

+0

你能請張貼的完整代碼。 – kaysush

+2

在Swing中有JFormattedTextField或DocumentFilter for plain JTextField – mKorbel

回答

3

您可以使用一個簡單的檢查:

if (!name.replaceAll("[0-9]", "").equals(name)) { 
    // name contains digits 
} 

replaceAll調用從該name所有數字。只有當沒有要刪除的數字時,equals檢查纔會成功。

請注意,在這種情況下拋出NumberFormatException會引起誤解,因爲異常具有非常不同的含義。

+0

感謝您的支持。現在它工作得很好。我傾向於使我的編碼複雜化。 –

+0

我明白,但在我的程序中使用比在我的編碼中多次嘗試和捕捉會更容易,這會導致我很大的困惑。 –

0

如果你想允許用戶只輸入字母,你可以這樣做:

if (name.matches("\\p{Alpha}+")) { 
    // name contains only letters 
} 
2

考慮使用JFormattedTextField或輸入驗證以防止在第一時間輸入數字的用戶。對於一次性項目而言,失去JOptionPane簡單性可能並不值得,但它爲最終用戶簡化了一些事情。

+0

適用於Swing JComponents的正確方法 – mKorbel

2

或者,你根本就沒有讓用戶把任何數值在textField。對於您需要創建自定義PlainDocumentNonNumericDocument並設置了JTextField對象的Document作爲定製NonNumericDocument

import java.awt.BorderLayout; 
import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.text.Document; 
import javax.swing.text.PlainDocument; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 

class NonNumericDocument extends PlainDocument 
{ 
    @Override 
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException 
    { 
     if (str == null) 
     { 
      return; 
     } 
     char[] arr = str.toCharArray(); 
     for (int i = 0; i < arr.length; i++) 
     { 
      if (Character.isDigit(arr[i]) || !Character.isLetter(arr[i]))//Checking for Numeric value or any special characters 
      { 
       return; 
      } 
     } 
     super.insertString(offs, new String(str), a); 
    } 
} 
//How to use NonNumericDocument 
class TextFrame extends JFrame 
{ 
    JTextField tf ; 
    public void prepareAndShowGUI() 
    { 
     tf = new JTextField(30); 
     tf.setDocument(new NonNumericDocument());//Set Document here. 
     getContentPane().add(tf,BorderLayout.NORTH); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     pack(); 
     setVisible(true); 
    } 
    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater (new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       TextFrame tFrame = new TextFrame(); 
       tFrame.prepareAndShowGUI(); 
      } 
     }); 
    } 
} 

您可以在代碼中將此NonNumericDocument與任何JTextField一起使用,而無需擔心明確處理non-numeric字符。

+1

適用於Swing JComponents的正確方法 – mKorbel

0

另一種方式來檢查它使用parseInt(String s)方法:

private boolean isNumber(String s) { 
    try { 
     Integer.parseInt(s); 
    } catch (Exception e) { 
     return false; // if it is not a number it throws an exception 
    } 
    return true; 
}