打印字符串时格式不正确

时间:2017-05-03 05:47:50

标签: java

尝试创建一个接收fileName的Madlibs程序并浏览该文件,并在text以<开头时查找并以>结束。例如,“看那个<名词>。” (忽略名词和<>之间的空格。 如果找到令牌,则应将其替换为text = user.nextLine()。但是当打印fullText时,程序可以正常工作,格式与.txt文件不同。它会丢失.txt文件中的新行字符。可以更改什么以确保格式相同。

import java.util.*;
import java.io.*;
public class MadLibs {
  public static void main ( String [] args){
     Scanner input = new Scanner (System.in);
    System.out.println("Enter file Name: ");    //file input
    String fileName = input.nextLine();

    String fileContent = readEntireFile(fileName);     //method call
    System.out.println(fileContent);
  }

  public static String readEntireFile(String fileName){
      Boolean fileOpened = true;
      File someFile = new File(fileName);
      Scanner user = new Scanner (System.in);
      Scanner inputFile = null;
      String text;
      String fullText = " ";

      try{
        inputFile = new Scanner (someFile);
      }
      catch( FileNotFoundException e){
        System.out.println("FILE NOT FOUND");
        fileOpened = false;
      }
      if(fileOpened){
        while(inputFile.hasNextLine()){
          text = inputFile.next();
          if (text.startsWith("<") && text.endsWith(">")) {     
                    String input = text.substring(1, text.length() - 1);     
                    String word = input.replace("-"," ");
                    System.out.println("Please input a: " + word);
                    text = user.nextLine();           


          }
          fullText = fullText + text + " ";   

        }

        inputFile.close();
        return fullText;  //returns the entire String 
      }
      return null;
    }
  }

0 个答案:

没有答案