String / int Exception Catch in Java

时间:2017-01-15 00:13:40

标签: java exception

我创建了一个演示注册程序,其中添加了一些用于测试的线程。用户名不能只是数字(例如用户名= 141235),但可能是(username = John124)。我调用了通用异常,但它没有阻止它。有人可以帮忙吗?

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();
        }
}
}

3 个答案:

答案 0 :(得分:0)

使用类似的东西。它将所有数字替换为空白。

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

答案 1 :(得分:0)

我无法调试您的程序,因为它似乎不完整。但是,如果您的目标的一部分是对用户名强制执行某些规则,那么您应该首先明确定义规则是什么。例如,是否允许“123456a”? (它有数字和alpha,但它也以数字开头)。然后您可以考虑使用正则表达式来表达您的规则并为您进行检查。以下程序假定某些规则:

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

答案 2 :(得分:-1)

将try语句放在if语句中。该语句应该具有charles.hasNextLine()作为它的条件。