2010-10-18 43 views
0
import java.io.*; 
import java.lang.*; 

public class Propogate1 
{ 

String reverse(String name) 
{ 
if(name.length()==0) 
    throw IOException("name"); 

String reverseStr=""; 
for(int i=name.length()-1;i>0;--i) 
{ 
    reverseStr+=name.charAt(i); 

} 
return reverseStr; 
} 

public static void main(String[] args)throws IOException 
{ 
String name; 
try 
{ 
     Propogate1 p=new Propogate1(); 
    p.reverse("java"); 

} 
finally 
{ 
System.out.println("done"); 
} 

} 

} 

我必須創建一個類propogate和main方法,它將調用reverse()。在這種情況下,如果name.length爲null,它將引發異常。如果它不爲null,它將反轉字符串。請幫助我錯誤在下面的代碼附近拋出IOException

+0

導入時,你不應該使用通配符包年齡。總是(在可以使用通配符時出現一些罕見情況)使用包名稱+要導入的類名稱(例如import java.io.IOException)。否則,您可能在使用不同的軟件包時出現相同的類名稱 – Dennis 2010-10-18 05:56:47

+0

也存在一些問題您的* for *循環中存在一個錯誤,在您遵循@ Guillaume的答案後需要修復 – JoseK 2010-10-18 05:59:09

+0

@JoseK:我已經刪除了「for循環錯誤」太 – ivorykoder 2010-10-18 06:17:52

回答

1

可能這是你需要的。

package reversestring; 

// import java.io.* is not needed here. 
// And if you want to import anything, 
// prefer specific imports instead and not entire package. 

// java.lang.* is auto-imported. You needn't import it explicitly.  

public class Propogate { 
    // There's no reason this method should be an object method. Make it static. 
    public static String reverse(String name) { 
    if (name == null || name.length() == 0) { 
     // RuntimeExceptions are preferred for this kind of situations. 
     // Checked exception would be inappropriate here. 
     // Also, the error message should describe the kind of exception 
     // occured. 
     throw new RuntimeException("Empty name!"); 
    } 
    // Idiomatic method of string reversal: 
    return new StringBuilder(name).reverse().toString(); 
    } 

    public static void main(String[] args) { 
    String name; 
    try { 
     name = Propogate.reverse("java"); 
     System.out.println("Reversed string: " + name); 
    } catch (RuntimeException rx) { 
     System.err.println(rx.getMessage()); 
    } finally { 
     // I don't get the point of `finally` here. Control will reach this 
     // point irrespective of whether string reversal succeeded or failed. 
     // Can you explain what do you mean by "done" below? 
     System.out.println("done"); 
    } 
    } 
} 

/*

輸出: -

反轉字符串:avaj

*/

+0

嗨,謝謝你已經清除了錯誤。現在在這個pgm我不想使用任何捕獲。沒有趕上,我必須定義我自己的例外,我也想最終使用。你能幫我這個現在 – Sumithra 2010-10-18 06:22:43

+0

更新了我的答案。 – ivorykoder 2010-10-18 07:08:02

+0

亞我明白了謝謝! – Sumithra 2010-10-18 08:24:03

1

您需要聲明哪些異常的方法拋出:方法聲明應該是:

String reverse(String name) throws IOException 
1

你必須把它扔之前創建例外:

if(name.length()==0) 
    throw new IOException("name"); 

而且主要不得拋出IOException。抓住它並將信息打印到System.err

相關問題