2016-11-17 63 views
1

您好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); 
    } 
} 
} 
+0

注意:我編輯了「c = c.substring(1)」到「c = c.substring(2)」對不起! –

+0

嘗試使用奇數和偶數長度輸入來調試該子字符串語句。 – nullpointer

+0

對不起,這是什麼意思?我應該使用調試器嗎? –

回答

1

看起來你需要檢查c然後再嘗試substring它......如果它的長度小於2,你會得到一個StringIndexOutOfBoundsException,因爲你試圖從索引2開始substring,但是索引2沒有存在。試試這個:

public int OneChar (String c) 
    { 

     if (c.equals ("")) 
      return 1; 
     else 
     { 
      char first = c.charAt (0); 
      System.out.println (first); 
      if(c.length() > 2) { 
       c = c.substring (2); 
       return OneChar (c); 
      } 
      return 1; 
     } 
    } 
0

你缺少檢查字符串長度是否大於2做子之前,

公衆詮釋OneChar(串c){

if (c.equals("")) 
     return 1; 
    else { 
     char first = c.charAt(0); 
     if (c.length() >= 2) { 
      c = c.substring(2); 
      System.out.println(first); 
      return OneChar(c); 
     } 
     return 0; 
    } 
}