我是 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); } }}
2 回答
茅侃侃
TA貢獻1842條經(jīng)驗 獲得超22個贊
Substring += " " + s.charAt(position);應該初始化為"". 您初始化空間并在方法之前添加兩個空格。getSubstring(s,1,1);事實上,它是第二個字符。也就是說,空格然后你會轉(zhuǎn)向數(shù)字,你會得到一個錯誤。
胡說叔叔
TA貢獻1804條經(jīng)驗 獲得超8個贊
乍一看我能看到的是 s.charAt(int index) 返回一個字符,所以你實際上需要檢查的是:s.charAt(0).equals('0'),第二,有更好的處理日期的方法,例如使用數(shù)據(jù)類型 Date,它允許您調(diào)用返回日/月/年的函數(shù)。希望能幫助到你。
添加回答
舉報
0/150
提交
取消
