parseXXX()
parseXXX()是SimpleDateFomat裏面的方法,有一個參數和兩個參數的方法。一個參數時會按照對象數據類型不同分爲parseInt(), parsefloat()和parsedouble(),將字符串參數變爲數字(整數、浮點數)。兩個參數時則是先將第一個參數變成整數,再以第二個參數指定的進制將這個整數變成十進制,即,若第二個參數爲N,則先假定第一個參數是N進制數,再將次N進制數轉化爲十進制數。注意,返回值只能是整數。
public class test {
public static void main(String args[]) {
String op="123";
int i=Integer.parseInt(op);
float f=Float.parseFloat(op);
double d=Double.parseDouble(op);
System.out.println(i);//結果是123
System.out.println(f);//結果是123.0
System.out.println(d);//結果是123.0
}
}
若字符串不能被轉換成數字(字符串裏有非數字的字符),則會報錯(如op="123s")
Exception in thread "main" java.lang.NumberFormatException: For input string: "123s"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
ValueOf()
ValueOf()方法也有三種數據類型對應的方法。Integer.valueOf(), Float.valueOf()、Double.valueOf()和String.valueOf()是把某一類型的值轉化爲Integer、Float、Double或String類型的。//op可以是int、float、double或String類型。
(注意:是Integer類型,而不是int類型,int類型是表示數字的簡單類型,Integer類型是一個引用的複雜類型。我也不懂,所以具體可以參考:https://blog.csdn.net/teacher_lee_zzsxt/article/details/79230501)
public class test {
public static void main(String args[]) {
String op="123";
int i=Integer.valueOf(op);
float f=Float.valueOf(op);
double d=Double.valueOf(op);
String s=String.valueOf(op);
System.out.println(i);//結果是123
System.out.println(f);//結果是123.0
System.out.println(d);//結果是123.0
System.out.println(s);//結果是123
}
}
若字符串不能被轉換成數字(字符串裏有非數字的字符),則會報錯(如op="123s")
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
i cannot be resolved to a variable
f cannot be resolved to a variable
d cannot be resolved to a variable
i cannot be resolved to a variable
f cannot be resolved to a variable
d cannot be resolved to a variable
toString()
toString()的作用是將數字轉換成字符串。
public class test {
public static void main(String args[]) {
String op="123";
int i=Integer.valueOf(op);
float f=Float.valueOf(op);
double d=Double.valueOf(op);
System.out.println(i);//結果是123
System.out.println(f);//結果是123.0
System.out.println(d);//結果是123.0
String s;
s=Integer.toString(i);//將Integer變成字符串
System.out.println(s);//結果是123
s=Float.toString(f);//將Float變成字符串
System.out.println(s);//結果是123.0
s=Double.toString(d);//將Double變成字符串
System.out.println(s);//結果是123.0
}
}
toString()的參數必須和對象是同一個類型,賦值的變量一定是字符串型,否則無法編譯。