2013-01-31 44 views
0

考慮以下代碼:如何在java中傳遞變量?

private static void colourRead(String s) throws IOException { 
    FileReader readhandle = new FileReader("C:\\****\\****"); 
    BufferedReader br = new BufferedReader(readhandle); 
    String line = null; 
    while ((line = br.readLine()) != null) { 
     ColourInput(); //there's an error here 
    } 

    br.close(); 
    readhandle.close(); 
} 

private static void ColourInput(String s) { 
    char letter; 

    String fullWord; 
    Scanner kb = new Scanner(System.in); 

    System.out.print("Enter whatever: "); 

    fullWord = kb.nextLine(); 
    System.out.println(fullWord); 

    for (int i = 0; i < fullWord.length(); i++) { 
     letter = fullWord.charAt(i); 
     switch (Character.toUpperCase(letter)) { 
     case 'A': { 
      Blue(); 
     } 
      break; 
     } 
    } 
} 

是否有可能對我來說,攜帶從colourRead方法

line 

變量,並以某種方式把它分配給在該

fullWord 

變量ColourInput()方法?

我想讀取文本文件,並輸出與每個字母關聯的某些顏色。我不想在colourRead方法中創建一個新的switch語句,因爲顯然這是一種糟糕的編程習慣。

請幫忙嗎?

如果你仍然不能確定我問我會重新編輯什麼

編輯:問題是,調用ColourInput(行)方法後,掃描儀的方法來在工作(原碼)。我不想刪除我的掃描器方法,我希望它'跳過'掃描器方法,並繼續進入for循環和切換語句。

+0

'ColourInput(line)'? –

+0

爲了響應您的編輯,您爲什麼希望它跳過掃描儀行,而不是隻刪除掃描儀行?如果你想要兩種方法的不同功能,請參閱下面的答案。它會爲閱讀器着色,並允許您仍然使用掃描儀方法。 – jzworkman

+0

我想讓它跳過掃描器行,因爲我想使用兩種不同的方法來使用switch語句。一種方法是接受用戶輸入(然後使用for循環和switch語句),另一種方法讀取文件(然後使用for循環和switch語句) – Adz

回答

1

如果我理解正確,您希望能夠使用ColourRead方法的結果重複ColourInput方法的功能。

private static void colourRead() throws IOException 
{ 
    FileReader readhandle = new FileReader("C:\\****\\****"); 
    BufferedReader br = new BufferedReader(readhandle); 
    String line = null; 
    while((line = br.readLine()) != null) 
    { 
     ColourText(line); //there's an error here 
    } 

    br.close(); 
    readhandle.close(); 
} 

private static void ColourInput() 
{ 

    String fullWord; 
    Scanner kb = new Scanner(System.in); 

    System.out.print("Enter whatever: "); 

    fullWord = kb.nextLine(); 
    System.out.println(fullWord); 
    ColourText(fullWord); 
} 

private static void ColourText(String text) 
{ 

    char letter; 
    for (int i = 0; i < text.length(); i++) 
    { 
     letter = text.charAt(i); 
     switch(Character.toUpperCase(letter)) 
     { 
      case 'A': 
      { 
      Blue(); 
      } 
      break; 
     } 
} 

這將讓你的顏色無論是從鍵盤(使用ColourText方法來改變顏色)的文件或輸入讀取文本。但正如其他人所提到的,你也應該添加到文件讀取代碼中。

編輯:你也可以從前兩個方法中刪除String s變量,因爲它們沒有被用在任何地方的方法中。

+0

在ColourText方法中,不識別字母變量。 – Adz

+0

對不起,這是一個複製粘貼錯誤,你只需要初始化變量。我已經更新了我的示例。 – jzworkman

3

你沒有通過串到你的ColourInput

呼叫嘗試

ColourInput(line);

還值得一提的是,你的代碼讀取該文件是不是安全的,你應該嘗試讀取文件,捕獲IOException並關閉finally子句中的文件,如果代碼在while循環中某處崩潰,則文件可能保持打開狀態