2014-01-23 4 views
0

안녕 나는이 자바 코드, 처음에 쓸 수있는 파일의 이름을 묻는 있도록 Scanner 클래스와 Java에서 next() 메서드를 사용하는 방법은 무엇입니까?

import java.io.*; 
import java.util.*; 
public class SongWriter 
{ 
    public static void main(String[] args) 
    { 
    PrintWriter outputStream = null; // Scope must be outside the try/catch structure 
    try 
    { 
     outputStream = new PrintWriter("Song.txt"); // new 
     FileOutputStream("Song.txt") 
    } 
    catch(FileNotFoundException e) 
    { 
     System.out.println("Error opening the file Song.txt."); 
     System.exit(0); 
    } 
    System.out.println("\n classical songs has many lines"); 
    System.out.println("\nNow enter the three lines of your Song."); 
    String line = null; 
    Scanner keyboard = new Scanner(System.in); 
    int count; 
    for (count = 1; count <= 3; count++) 
    { 
     System.out.println("\nEnter line " + count + ": "); 
     line = keyboard.nextLine(); 
     outputStream.println(count + "\t" + line); 
    } 
    outputStream.close(); 
    System.out.println("\nYour Song has been written to the file Song.txt.\n"); 
    } // end of main 
} // end of class 

가 어떻게 프로그램을 조정 할 수 있습니다. Scanner 클래스와 next() 메서드를 사용하십시오. 파일 이름을 접미사 .txt로 끝나야한다는 것을 독자에게 알린 후 문자열 변수로 파일 이름을 읽습니다. 예 : - 파일 이름이 Haiku1.txt, Haiku2.txt 및 Haiku3.txt 인 노래.

+0

공백을 추가하여 더 읽기 쉽게 만들면 매우 유용합니다. – Deena

+0

Scanner 클래스의 Javadocs를 읽었습니까? –

+0

@Deena 안녕하세요, 죄송합니다. – Sameena

답변

0

거의 들었습니다.

Scanner keyboard = new Scanner(System.in); 
System.out.println("Enter first file name:"); 
String first = keyboard.nextLine(); 
System.out.println("Enter second file name:"); 
String second = keyboard.nextLine(); 
System.out.println("Enter third file name:"); 
String third = keyboard.nextLine(); 
//and so on and continue whatever you want to do.. 

편집 : 귀하의 의견을 듣고 나서.

먼저 StringBuilder에 3 줄을 저장 한 다음 쓸 파일 이름을 묻습니다. 이제 당신은 가사와 파일 이름을 가지고 있습니다. 당신은 당신이했던 것처럼 사용자가 대신 (그것을 하드 코딩 입력 된 파일 이름을 사용할 수 있도록

String fileName1; 
Scanner keyboard = new Scanner(System.in); //creates Scanner object 
System.out.print ("Enter the name of the file. The file should end in the suffix .txt") //prompt the user to enter the file name 
fileName1 = keyboard.next(); //store the name of the file 

당신은 try/catch 블록 전에이 작업을 수행해야한다 : 사용자의 입력을 얻기 위해 스캐너 클래스를 사용

+0

stringbuilder에 3 행을 저장하면 어떻게됩니까? – Sameena

+0

먼저 프로그램에서 가사를 쓰고 파일 이름에 가사를 씁니다. 가사를 계속해서 StringBuilder에 추가해야하고 파일 이름을 물어보고 그 파일에'StringBuilder'를 씁니다. –

0

여기 song.txt와 함께).

사용자에게 필요한만큼 많은 파일 이름에 대해이 방법을 사용하라는 메시지를 표시 할 수 있습니다.

+0

fileName1은 생성 될 파일의 ​​이름이됩니까? 그래서 코드를 실행할 때 파일 이름을 입력하십시오. 여기서 무슨 일이 일어 났는지 설명해 주시겠습니까? 죄송합니다. 좀 이상한 자바 – Sameena

+0

프로그램은 사용자에게 .txt 확장명의 파일 이름을 입력하라는 요청을 표시합니다. Scanner 클래스의 .next() 메서드를 사용하여 변수를 fileName1 변수에 저장할 수 있습니다. 그런 다음 파일 이름으로 song.txt를 하드 코딩하는 대신 파일 이름을 저장 한 변수를 사용할 수 있습니다. – Deena

+0

또한 outputStream = new PrintWriter ("Haiku.txt")가 필요합니까? Haiku1.txt 및 Haiku2.txt 용? – Sameena

관련 문제