国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java Java基礎(chǔ) java判斷變數(shù)是不是數(shù)字方法總結(jié)

java判斷變數(shù)是不是數(shù)字方法總結(jié)

Nov 25, 2019 am 10:34 AM
java

java判斷變數(shù)是不是數(shù)字方法總結(jié)

java判斷變量是不是數(shù)字方法:(相關(guān)視頻課程推薦:java視頻教程

1、用JAVA自帶的函數(shù)

public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
   System.out.println(str.charAt(i));
   if (!Character.isDigit(str.charAt(i))){
    return false;
   }
}
return true;
}

2、用正則表達式

首先要import java.util.regex.Pattern 和 java.util.regex.Matcher

public boolean isNumeric(String str){
   Pattern pattern = Pattern.compile("[0-9]*");
   Matcher isNum = pattern.matcher(str);
   if( !isNum.matches() ){
       return false;
   }
   return true;
}

3、使用org.apache.commons.lang

org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解釋:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null)   = false
StringUtils.isNumeric("")     = true
StringUtils.isNumeric(" ")   = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null

上面三種方式中,第二種方式比較靈活。

第一、三種方式只能校驗不含負號“-”的數(shù)字,即輸入一個負數(shù)-199,輸出結(jié)果將是false;

而第二方式則可以通過修改正則表達式實現(xiàn)校驗負數(shù),將正則表達式修改為“^-?[0-9]+”即可,修改為“-?[0-9]+.?[0-9]+”即可匹配所有數(shù)字。

如果我輸入的是"a“,它能識別出來這個不是數(shù)字,該怎么寫?

import java.io.* ;
import java.util.* ;
public class Test{
public static void main(String [] args) throws Exception{
System.out.println("請輸入數(shù)字:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   String line=br.readLine();
    if(line.matches("\\d+"))     //正則表達式 詳細見java.util.regex 類 Pattern
   System.out.println("數(shù)字");
   else
   System.out.println("非數(shù)字");
}
}

("\d")是數(shù)字0-9 ("\\d+")是什么意思?

正則表達式用兩個斜杠表示一個斜杠,后面跟著一個加號表示出現(xiàn)一次或多次,完整的意思就是整個字符串中僅包含一個或多個數(shù)字。

4、判斷ASCII碼值

 public static boolean isNumeric0(String str){
  for(int i=str.length();--i>=0;){
   int chr=str.charAt(i);
   if(chr<48 || chr>57)
    return false;
  }
  return true;
 }

5、逐個判斷str中的字符是否是0-9

 public static boolean isNumeric3(String str){
  final String number = "0123456789";
  for(int i = 0;i
            if(number.indexOf(str.charAt(i)) == -1){  
             return false;  
            }  
  }  
  return true;
 }

6、捕獲NumberFormatException異常

 public static boolean isNumeric00(String str){
  try{
   Integer.parseInt(str);
   return true;
  }catch(NumberFormatException e){
   System.out.println("異常:\"" + str + "\"不是數(shù)字/整數(shù)...");
   return false;
  }
 }

ps:不提倡使用方法6,原因如下:

1、NumberFormatException是用來處理異常的,最好不要用來控制流程的。

2、雖然捕捉一次異常很容易,但是創(chuàng)建一次異常會消耗很多的系統(tǒng)資源,因為它要給整個結(jié)構(gòu)作一個快照。

看一下JDK源碼:

 public static long parseLong(String s,int radix)  
         throws NumberFormatException  
 {  
    if(s == null){  
       throw   new   NumberFormatException("null");  
    }  
    if(radix < Character.MIN_RADIX){  
           throw new NumberFormatException("radix " + radix +
           " less than Character.MIN_RADIX");  
    }  
    if(radix > Character.MAX_RADIX){  
           throw new NumberFormatException("radix " + radix +
           " greater than Character.MAX_RADIX");  
    }  
    long result = 0;  
    boolean negative = false;
    int i = 0,max = s.length();  
    long limit;  
    long multmin;  
    int digit;
    if(max > 0){  
     if(s.charAt(0) == &#39;-&#39;){  
      negative = true;  
      limit = Long.MIN_VALUE;
      i++;
     }else{
      limit = -Long.MAX_VALUE;
     }  
     multmin = limit / radix;
     if(i < max){  
      digit = Character.digit(s.charAt(i++),radix);  
      if(digit < 0){
            throw new NumberFormatException(s);  
      }else{  
            result = -digit;
      }  
     }  
     while(i < max){  
      // Accumulating negatively avoids surprises near MAX_VALUE
      digit = Character.digit(s.charAt(i++),radix);  
      if(digit < 0){  
       throw new NumberFormatException(s);  
      }  
      if(result < multmin){  
       throw new NumberFormatException(s);  
      }  
      result *= radix;  
      if(result < limit + digit){  
       throw new NumberFormatException(s);  
      }  
      result -= digit;  
    }  
    }else{  
     throw   new   NumberFormatException(s);  
    }  
    if(negative){  
     if(i > 1){  
      return result;
     }else{  
      throw new NumberFormatException(s);  
     }  
    }else{  
     return   -result;  
    }  
 }

可以看出來jdk里也是一個字符一個字符的判斷,如果有一個不是數(shù)字就拋出NumberFormatException,所以還不如這個工作由我們自己來做,還省得再拋出一次異常。

更多java相關(guān)文章請關(guān)注java基礎(chǔ)教程

以上是java判斷變數(shù)是不是數(shù)字方法總結(jié)的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔相應(yīng)的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1502
276
如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務(wù),必須先關(guān)閉自動提交模式,再執(zhí)行多個操作,最後根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開始事務(wù);2.執(zhí)行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時應(yīng)使用try-with-resources管理資源,妥善處理異常並關(guān)閉連接,避免連接洩漏;此外建議使用連接池、設(shè)置保存點實現(xiàn)部分回滾,並保持事務(wù)盡可能短以提升性能。

了解Java虛擬機(JVM)內(nèi)部 了解Java虛擬機(JVM)內(nèi)部 Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

如何使用Java的日曆? 如何使用Java的日曆? Aug 02, 2025 am 02:38 AM

使用java.time包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當前日期時間;3.使用of()方法創(chuàng)建特定日期時間;4.利用plus/minus方法不可變地增減時間;5.使用ZonedDateTime和ZoneId處理時區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

比較Java框架:Spring Boot vs Quarkus vs Micronaut 比較Java框架:Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

前形式攝取,quarkusandmicronautleaddueTocile timeProcessingandGraalvSupport,withquarkusoftenpernperforminglightbetterine nosserless notelless centarios.2。

了解網(wǎng)絡(luò)端口和防火牆 了解網(wǎng)絡(luò)端口和防火牆 Aug 01, 2025 am 06:40 AM

NetworkPortSandFireWallsworkTogetHertoEnableCommunication whereSeringSecurity.1.NetWorkPortSareVirtualendPointSnumbered0-655 35,with-Well-with-Newonportslike80(HTTP),443(https),22(SSH)和25(smtp)sindiessingspefificservices.2.portsoperateervertcp(可靠,c

垃圾收集如何在Java工作? 垃圾收集如何在Java工作? Aug 02, 2025 pm 01:55 PM

Java的垃圾回收(GC)是自動管理內(nèi)存的機制,通過回收不可達對象釋放堆內(nèi)存,減少內(nèi)存洩漏風險。 1.GC從根對象(如棧變量、活動線程、靜態(tài)字段等)出發(fā)判斷對象可達性,無法到達的對像被標記為垃圾。 2.基於標記-清除算法,標記所有可達對象,清除未標記對象。 3.採用分代收集策略:新生代(Eden、S0、S1)頻繁執(zhí)行MinorGC;老年代執(zhí)行較少但耗時較長的MajorGC;Metaspace存儲類元數(shù)據(jù)。 4.JVM提供多種GC器:SerialGC適用於小型應(yīng)用;ParallelGC提升吞吐量;CMS降

比較Java構(gòu)建工具:Maven vs. Gradle 比較Java構(gòu)建工具:Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

以身作則,解釋說明 以身作則,解釋說明 Aug 02, 2025 am 06:26 AM

defer用於在函數(shù)返回前執(zhí)行指定操作,如清理資源;參數(shù)在defer時立即求值,函數(shù)按後進先出(LIFO)順序執(zhí)行;1.多個defer按聲明逆序執(zhí)行;2.常用於文件關(guān)閉等安全清理;3.可修改命名返回值;4.即使發(fā)生panic也會執(zhí)行,適合用於recover;5.避免在循環(huán)中濫用defer,防止資源洩漏;正確使用可提升代碼安全性和可讀性。

See all articles