簡體   English   中英

當用戶輸入數字而不是字符串時顯示錯誤

[英]Display an error when user enters a number instead of a string

我試圖在此上找到一些東西,但是在過去的一個小時的搜索中沒有看到任何相關的東西。 我試圖在用戶嘗試輸入數字而不是字符串時引發錯誤。

當用戶輸入字符串而不是int時,我發現了足夠的資源來了解如何引發和出錯,但是反之則無所作為。

我將快速編寫一些代碼

import java.util.Scanner;

public class ayylmao {

    public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your first name");
            String AyyLmao = scan.nextLine();
            System.out.println("Your first name is " + AyyLmao);
/*
Want it to say something like "Error: First character must be from the alphabet!" if the user tries to enter a number.
*/

        }
    }

嘗試這個:

public static boolean isIntegerParseInt(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException nfe) {}
    return false;
}

如果它只是您感興趣的第一個字符,則可以使用如下測試:

if (AyyLmao.charAt(0) >= '0' && AyyLmao.charAt(0) <= '9'){
  /* complain here */
}

正如您顯然已經發現的那樣,對整個字符串進行測試將是:

try{
  Integer.parseInt(AyyLmao);
  /* complain here */
} catch(NumberFormatException ex){
  /* this would be OK in your case */
}

使用正則表達式"^\\\\d"找出字符串開頭是否有數字。

例如,為了檢查名稱的開頭是否是數字:

String regex = "^\\d";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(yourInput);
if(m.find()) {
   // Your input starts with a digit
}

這是開始使用正則表達式的好地方: http : //www.vogella.com/tutorials/JavaRegularExpressions/article.html

private static String acceptName() {
        // TODO Auto-generated method stub
        Boolean flag = Boolean.TRUE;
        String name = "";
        while (flag) {
            Scanner scan = new Scanner(System.in);
            System.out.println("enter name : ");
            name = scan.nextLine();
            try {
                Integer no = Integer.parseInt(name);
                System.out.println("you have entered number....");
            } catch (NumberFormatException e) {
                flag = Boolean.FALSE;

            }
        }
        return name;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM