2017-01-15 45 views
-1

我創建了一個演示註冊程序,其中添加了一些用於測試的線程。用戶名不能只是數字(例如用戶名= 141235),但它可能是(用戶名= John124)。我調用了泛型異常,但並不妨礙它。誰能幫忙?字符串/ int異常在Java中捕獲

package com.company; 


import java.util.Scanner; 


public class tested extends Thread { 
    Scanner charles = new Scanner(System.in); 
    @Override 
    public void run() { 
     System.out.println("New User Sign On"); 
     System.out.println("==================="); 
     System.out.println("Please Enter A New User Name"); 
     try{ 
     String choose = charles.nextLine(); 
      System.out.println("Submitting....."); 
     Thread.sleep(2000); 
      System.out.println("Cross Referencing Username......"); 
      //Checking for username in database 
      Thread.sleep(2000); 
      System.out.println("New Username Accepted"); 
      //Username added to database 
      Thread.sleep(900); 
      System.out.println("Your new username is "+choose+". Now enjoy our FREE services."); 
    }catch (Exception e){ 
      getStackTrace(); 
     } 
} 
} 
+2

_「我已在通用的異常調用,但它不會阻止它」 _ - 對不起,這不是可解析英語。你能澄清你的意思嗎?如果出現異常,請包括完整的堆棧跟蹤。 –

回答

-1

將try語句放在if語句中。該聲明應該具有charles.hasNextLine()作爲條件。

+0

你能解釋這是如何回答這個問題的嗎?您可以提供示例代碼來說明您的觀點。 – soundslikeodd

0

使用類似這樣的東西。它將所有數字替換爲空白。

do { 
System.out.println("Please enter a username"); 
choose=charles.nextLine(); 
} while (choose.replaceAll("\\d", "").equals("")) 
0

我無法調試您的程序,因爲它看起來不完整。但是,如果您的目標的一部分是對用戶名執行某些規則,那麼您應該首先明確規定哪些規則。例如,是否允許「123456a」? (它有兩個數字和阿爾法,但它也開始於一個數字)。然後你可以考慮使用正則表達式來表達你的規則併爲你做檢查。下面的程序呈現一定的規律:

public class ValidUsername { 

    public static void main(String[] args) { 
     String[] tests = { 
       "123456"  // expect invalid: not start with alpha 
       , "a123456"  // expect valid 
       , "123456a"  // expect invalid: not start with alpha 
       , ""   // expect invalid: not start with alpha 
       , "a"   // expect valid 
       , "a12345678" // expect invalid: too many characters 
     }; 

     /* 
     * username must start with an alpha characters [a-zA-Z], 
     * and then follow by not more than 7 alphanumeric characters 
     */ 
     String regex = "[a-zA-Z]\\w{0,7}"; 
     for (String test: tests) { 
      boolean match = test.matches(regex); 
      System.out.format("test %10s %6s a valid username%n" 
        , test, (match ? "is" : "is not")); 
     } 
    } 

} 

輸出這一方案的:

test  123456 is not a valid username 
test a123456  is a valid username 
test 123456a is not a valid username 
test   is not a valid username 
test   a  is a valid username 
test a12345678 is not a valid username