2014-04-20 1 views
0

그래서 내가이 작동하는 동안

public static Scanner fileWriter() 
{ 
    Scanner sc = new Scanner(System.in); 
    System.out.println("What is the name of the file? (succeeded by .txt)"); 
    //String firs = sc.nextLine(); 
    try 
    { 
    Scanner scanner = new Scanner(new File("Test.txt")); 
    } 
    catch(IOException e) 
    { 
    System.out.println("Io exception" + e.getMessage()); 
    } 
    return scanner; 
} 

을 원하는 특정 파일, 스캐너를 반환, 내가 함께 문제가하고있는 유일한 것은 '반환 스캐너'입니다.

오류 내가 뭘 잘못

return scanner; 
    ^

을 "기호를 찾을 수 없습니다"인가? ! :(감사

+3

변수의 범위는 * scope *입니다. 특히, 둘러싸는 블록에. –

답변

1

이 줄 :

Scanner scanner = new Scanner(new File("Test.txt")); 

는 괄호 안에 그러므로 외부에서 볼 수 있도록하려면 앞에 try :

앞에 변수를 선언하십시오.
Scanner scanner; 

다음의 try 블록 내부에, 단지 차이는 유형의 이름을 포함하지 않는다는 것입니다 (선언하지 않습니다, 그것은 할당; 할당 문이됩니다.)

scanner = new Scanner(new File("Test.txt")); 
+0

감사합니다 ... 왜 내 질문에 downvoted? – user3543629

0

scanner는 try 블록의 범위 밖에 볼 수 없습니다 당신은 대신 다음을 수행 할 수 :.

public static Scanner fileWriter() 
{ 
    Scanner sc = new Scanner(System.in); 
    System.out.println("What is the name of the file? (succeeded by .txt)"); 
    String fileName = sc.nextLine(); 
    try 
    { 
     return new Scanner(new File(fileName)); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Io exception" + e.getMessage()); 
    } 
    return null; 
}