【发布时间】:2018-11-01 16:08:14
【问题描述】:
我是 Java 新手。我一直在尝试运行一个程序,但它给了我这个错误。我不明白为什么它不起作用。我的输入绝对是一个字符串,该方法返回一个 int。
所以我很困惑为什么会出现格式异常?感谢任何可以提供帮助的人。
public class TestAA3 {
public static void main(String[] args) {
int day = getDay("04/09/2034");
System.out.print(day);
}
public static String getSubstring( String s, int i, int j) {
// declaring the String that will eventually be modified and returned by the method
String Substring = " ";
// error message
if (j<i) {
throw new IllegalArgumentException("The second integer must be greater than the first");
} else {
// defining the limits of the new string
for ( int position = i;position<=j; position++) {
// new value of the String
Substring += " " + s.charAt(position);
}
return Substring;
}
}
// calling getSubstring and defining the position inside the string of the int that will be returned
public static int getDay(String s) {
if (s.charAt(0)==0){
String dayString = getSubstring(s,1,1);
return Integer.valueOf(dayString);
} else {
String dayString = getSubstring(s,0,1);
return Integer.valueOf(dayString);
}
}
}
【问题讨论】:
-
java.lang.NumberFormatException: For input string: " 0 4"" " 不是空字符串,而是包含空格的字符串。请改用""。 -
你不必实现
getSubString,Java 已经有这个:s.subString()。你甚至做错了。然后,仔细检查你给 subString 的数字,它们也是错误的。使用Javadoc 作为参考。 -
你可能想要
Character.getNumericValue(s.charAt(0)) == 0而不是s.charAt(0)==0。 -
@OHGODSPIDERS 你是对的!!!谢谢!!!
标签: java exception numberformatexception