[英]NumberFormatException when converting Integer String in Java
[英]Java: NumberFormatException in converting string to integer
我想從文本框中檢索值並將其轉換為整數。 我編寫了以下代碼,但拋出了NumberFormatException
。
String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
對System.out.println
的第一次調用將顯示數字,但轉換為整數會出現異常。 我究竟做錯了什么?
您的文本框可能包含帶有空格的數字。 嘗試遵循以下已編輯的代碼。 您需要先修剪TextBox值,然后才能將其轉換為Integer。 還要確保該值不超過整數范圍。
String nop=(no_of_people.getText().toString().trim());
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
嘗試這個:
int nop1 = Integer.parseInt(no_of_people.getText().toString().trim());
System.out.println(nop1);
我建議先將String中的所有non-digit characters
替換成int
:
replaceAll("\\D+", "");
您可以使用以下代碼:
String nop=(no_of_people.getText().toString().replaceAll("\\D+", ""));
System.out.printf("nop=[%s]%n", nop);
int nop1 = Integer.parseInt(nop);
System.out.printf("nop1=[%d]%n", nop1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.