如何在Java中使用Scanner类及其next()方法?

时间:2014-01-23 01:13:30

标签: java

嗨,我有这个Java代码,

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。

2 个答案:

答案 0 :(得分: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中,然后要求写入文件名。现在你有了歌词和文件名。

答案 1 :(得分:0)

使用Scanner类从用户那里获得输入:

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一样)。

您可以根据需要以这种方式提示用户输入任意数量的文件名。