2014-01-23 42 views
0

您好我有這樣的Java代碼,如何在Java中使用Scanner類及其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.. 

編輯:在您的評論後。

首先將這3行存儲在StringBuilder中,然後詢問要寫入的文件名。現在你有歌詞和文件名。

+0

你如何在一個stringbuilder中存儲3行? – Sameena

+0

我明白,首先你的程序要求歌詞,然後用文件名將這些歌詞寫入。您需要繼續將歌詞附加到「StringBuilder」,然後您將要求輸入文件名並將該「StringBuilder」寫入該文件。 –

0

使用掃描儀類從用戶那裏得到輸入:

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塊之前這樣做,這樣你可以使用用戶輸入的,而不是硬編碼(像你這樣的文件名這裏用song.txt)。

您可以用這種方式提示用戶輸入儘可能多的文件名稱。

+0

fileName1將成爲我將創建的文件的名稱?所以當我執行代碼時,即時獲取輸入文件的名稱?你能解釋一下這裏發生了什麼嗎?對不起我有點新來的java – Sameena

+0

程序會向用戶顯示一個請求,輸入擴展名爲.txt的文件的名稱。您可以使用Scanner類的.next()方法將其存儲在變量fileName1中(或者您稱之爲變量的任何內容)。然後,您可以使用存儲文件名的變量來代替將song.txt硬編碼爲文件的名稱。 – Deena

+0

我是否還需要outputStream = new PrintWriter(「Haiku.txt」);爲Haiku1.txt和Haiku2.txt? – Sameena

相關問題