您好StackOverflow用戶,我目前在java上的HS課程,所以我是一個java的新手至少可以說。現在,爲了我自己的使用,我正在編寫一個程序來接受用戶輸入,並遞歸地打印出其他每個字母,而沒有導入任何其他類,但Scanner。我的代碼適用於奇數個字符,但不適用於偶數個字符。爲什麼是這樣,你能提出一個簡單的解決方案,但沒有所有這些我不明白的抓/扔東西?我的代碼發佈在下面。謝謝,-A初學Java的編碼器遞歸地打印每一個其他字符
import java.util.Scanner;
public class PrintChars
{
private String chunk;
public PrintChars ()
{
chunk = "";
}
public static void main (String [] args)
{
PrintChars p = new PrintChars ();
p.GetPhrase ();
p.Deconstruct ();
}
public void GetPhrase ()
{
Scanner console = new Scanner (System.in);
do
{
System.out.print ("\n\nEnter a phrase: ");
chunk = console.nextLine ();
} while (chunk == null);
System.out.println ("\n\n");
}
public void Deconstruct ()
{
OneChar (chunk);
System.out.println ("\n\n");
}
public int OneChar (String c)
{
if (c.equals (""))
return 1;
else
{
char first = c.charAt (0);
c = c.substring (2);
System.out.println (first);
return OneChar (c);
}
}
}
注意:我編輯了「c = c.substring(1)」到「c = c.substring(2)」對不起! –
嘗試使用奇數和偶數長度輸入來調試該子字符串語句。 – nullpointer
對不起,這是什麼意思?我應該使用調試器嗎? –