2012-11-04 40 views
0

我一直在爲課堂做一個小型項目,它完美無缺地運行,但是當它與班級的汽車測試人員進行對抗時,它會返回2無線發現的錯誤。詢問課程的工作人員,他們說這可能是因爲我試圖掃描一條線時沒有存在,但我試圖打印所有我的掃描,並沒有發現這樣的事情。 這就是我有掃描在我的代碼:掃描線是否逃跑?

Scanner sc = new Scanner(System.in); 
    String sentence; 
    int choice; 

    System.out.println("Please enter a sentence:"); 
    sentence = sc.nextLine(); 

    printMenu(); // calls a function to print the menu. 

    // gets the require action 
    System.out.println("Choose option to execute:"); 
    choice = sc.nextInt(); 
    sc.nextLine(); 

(我試過有和沒有最後sc.nextLine)

static void replaceStr(String str) 
{ 
    String oldWord, newWord; 
    Scanner in = new Scanner(System.in); 

    // get the strings 
    System.out.println("String to replace: "); 
    oldWord = in.nextLine(); 
    System.out.println("New String: "); 
    newWord = in.nextLine(); 

    // replace 
    str = str.replace(oldWord, newWord); 
    System.out.println("The result is: " + str); 
    in.close(); 
} 
static void removeNextChars(String str) 
{ 
    Scanner in = new Scanner(System.in); 
    String remStr; // to store the string to replace 
    String tmpStr = ""; //the string we are going to change. 
    int i; // to store the location of indexStr 

    // gets the index 
    System.out.println("Enter a string: "); 
    remStr = in.nextLine(); 
    i=str.indexOf(remStr); 

    in.close(); // bye bye 

    if (i < 0) 
    { 
     System.out.println("The result is: "+str); 
     return; 
    } 

    // Build the new string without the unwanted chars. 
    /* code that builds new string */ 

    str = tmpStr; 
    System.out.println("The result is: "+str); 
} 

任何想法如何行可以在這裏泄露?

+0

確切的錯誤是什麼? –

+0

你看了[掃描儀沒有線發現異常](http://stackoverflow.com/questions/7688710/scanner-no-line-found-exception) –

+0

理查德 - 代碼不會給我錯誤和按預期工作。班級的自動測試人員會說「找不到線路」,而無需詳細說明。是的,我已經看過了。但感謝您的幫助。 – Nescio

回答

4

這是問題所在。您在多個地方使用in.close();(方法中最後一條語句爲replaceStr方法,中間爲removeNextChars方法)。當您使用close()方法關閉scnaner時,它也會關閉InputStream (System.in)。 InputStream不能在程序中重新打開。

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

任何掃描儀關閉將導致進入異常NoSuchElementException異常後讀取嘗試。

當程序完成後,請關閉掃描儀一次。

編輯:掃描儀關閉/用法:

在YOUT主要功能:

Scanner sc = new Scanner(System.in); 
    .... 
    ..... 
    replaceStr(Scanner sc, String str); 
    ..... 
    .... 
    removeNextChars(Scanner sc ,String str); 
    .... 
    .... 
    //In the end 
    sc.close(); 


static void replaceStr(Scanner in, String str){ 
    //All the code without scanner instantiation and closing 
    ... 
} 

static void removeNextChars(Scanner in, String str){ 
    //All the code without scanner instantiation and closing 
    ... 
} 

你應該都不錯。

+0

哦,那我該如何在功能裏面使用掃描儀? – Nescio

+0

@Nescio只是不要關閉它們 –

+0

只需將掃描儀作爲參數傳遞給你的函數。讓我更新答案。 –