字元串轉換成其他基本類型,以及包裝類的自動裝箱、拆箱 ...
字元串轉換成其他基本類型,以及包裝類的自動裝箱、拆箱
1 package com.example; 2 import java.util.Scanner; 3 import java.lang.*; 4 /** 5 * GuessDemo.java Description:判斷輸入的字元串是整數?小數? 6 * 7 * @author raizoo 8 * Created on 17-7-18 下午10:23 9 * @version 1.0 10 * @since JDK8.0 11 * 12 * @thows Exception: 無 13 */ 14 public class GuessDemo { 15 public static void main(String[] args){ 16 //輸入字元串 17 Scanner scan = new Scanner(System.in); 18 System.out.print("輸入字元串:"); 19 String target = scan.nextLine(); //輸入字元串 20 System.out.println(); 21 22 /* 23 * parseInt/parseDouble Description: 包裝類-裝箱/拆箱 24 * 其中,Integer.parseInt(String source) 解析字元串,轉換為int型 25 * Double.parseDouble(String source) 解析字元串,轉換為double型 26 * @param String source 27 * @return 轉換成的對應類型,如例中int/double 28 * @thows Exception: 無 29 */ 30 if(target.matches("\\d+")){ //判斷輸入字元串是整數? 31 int integ = Integer.parseInt(target); 32 System.out.println("是整數:"+integ); 33 }else if(target.matches("\\d+\\.\\d+")){ //判斷輸入字元串是小數 34 double doub = Double.parseDouble(target); 35 System.out.println("是小數:"+doub); 36 }else{ 37 System.out.println("不是數字"); 38 } 39 } 40 }