我的課是關於遞歸的章節,介紹Java的第18章。所以這就是它所說的:使用遞歸,從數字和字母的字符串中獲取最大整數?
「對於這個賦值,你將編寫兩個遞歸函數,它們都將解析由數字和數字組成的任何長度字符串。兩個函數應該在同一個類中,並且具有以下簽名「。
現在第一個是int sumIt(String s)來對給定字符串中的整數進行求和。我完成了這部分,你只需要看每個字符,看看它是否是一個數字,然後將其添加到總數,如果是這樣的話。然後在返回中,回想一下刪除了該char的函數。
第二個函數是int findMax(String s,int max)。所以基本上我認爲它會起作用的是,你以max 0開始,然後你在返回中再次調用函數,並且每次檢查下一個int是否大於max,如果是,則替換。我原本寫這個和第一個函數非常相似(查看我的代碼),但後來我意識到,在這個函數中,你不能一個字符一個字符。如果字符串是「xg12zz128-p/9」,則max應該是128.似乎沒有一種簡單的方法可以獲取字符串中的下一個整數。我不知道該怎麼做。
這裏是我的代碼:
public class Finder {
public int sumIt(String s) {
int total = 0;
if(s.length() > 0) { // checks that the string still has characters
if(s.substring(0, 1).matches("[0-9]")) { // checks if the first character is a number
total += Integer.parseInt(s.substring(0, 1)); // if num, parses into integer and adds it total
return total + sumIt(s.substring(1)); // return total and use recursursion to continue searching the string for ints
}
else {
return total + sumIt(s.substring(1)); // needed this else clause in case the char was not a number
}
}
else {
return total; // return total when there are no more characters
}
}
public int findMax(String s, int max) {
if (s.length() > 0) { // checks for characters
if(s.substring(0, 1).matches("[0-9]")) { // checks for number
int a = Integer.parseInt(s.substring(0, 1)); // parse num to int
if(a > max) {
return findMax(s.substring(1), a); // if the new int is bigger, we call the function again with that set as max
}
else return findMax(s.substring(1), max); // else we just use the old max
}
else return findMax(s.substring(1), max); // in case its not a num
}
else return max; // return max when all characters are gone.
}
}
,然後這裏是正在使用JUnit測試文件。可能不需要看到這段代碼,但至少可以看到答案的例子。
package week4.Whitelaw;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestRecursion
{
@Test
public void testSumIt()
{
Finder finder = new Finder();
assertEquals(6, finder.sumIt("1d2d3d"));
assertEquals(10, finder.sumIt("55"));
assertEquals(0, finder.sumIt("xx"));
assertEquals(1, finder.sumIt("00001"));
assertEquals(3, finder.sumIt("x0x0w1y2"));
assertEquals(21, finder.sumIt("123456"));
assertEquals(21, finder.sumIt("x123456x"));
assertEquals(7, finder.sumIt("1ggggg60"));
}
@Test
public void testMax()
{
Finder finder = new Finder();
// assume max is the smallest possible number
int max = 0;
assertEquals(12, finder.findMax("12x8",max));
assertEquals(88, finder.findMax("012x88",max));
assertEquals(100, finder.findMax("012x88ttttt9xe33ppp100",max));
assertEquals(128, finder.findMax("128",max));
assertEquals(0, finder.findMax("abcdef",max));
assertEquals(123456, finder.findMax("123456",max));
assertEquals(2, finder.findMax("x2x1x",max));
}
}
任何幫助將不勝感激!!
歡迎來到StackOverflow。請花點時間訪問[幫助]並閱讀[問]。形式問題「這是我的代碼,請調試」被認爲是無關緊要的。 StackOverflow不是討論,教程或調試網站。這種方式的工作原理是,你需要描述你遇到的問題,清楚地解釋你所嘗試的以及你不瞭解的內容。至少您應該已經在IDE調試器中逐步瞭解代碼,並能夠識別出與您的期望不符的結果。 –
而索引at處的字符是數字,則增加索引。如果它不是一個數字,那麼它之前的所有數字都是一個數字。 – Tibrogargan
似乎我們不需要考慮領先的負數?在「-29z4」中,最大值是29,而不是4? –