将扫描仪文件转换为包含Java中输出的整个文件的字符串

时间:2018-11-13 01:03:43

标签: java string loops

我正在研究一个MabLibs项目,该项目应遍历文件,提示您输入<>块中包含的所有内容,并允许您覆盖到新文件。

我无法弄清楚如何使用扫描仪读取文件并将其转换为字符串,因此我可以使用.length()方法在文件中循环进行for循环以找到这些<>块。

我只能使用Scanner,而不能使用数组列表,因此,不幸的是,for循环是实现此目的的唯一方法。

代码如下:

import java.io.*;
import java.util.*;

public class MadLibs {

public static void main(String[] args)
        throws FileNotFoundException {
            intro();
            madLib();


}

public static void intro() {
    System.out.println("Welcome to the game of Mad Libs.");
    System.out.println("I will ask you to provide various words");
    System.out.println("and phrases to fill in a story.");
    System.out.println("The result will be written to an output file.");
    System.out.println();
}


public static void madLib() throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
    String r = input.next();
    while (!(r.equalsIgnoreCase("c") || r.equalsIgnoreCase("v")
    || r.equalsIgnoreCase("q"))) {
        System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
    }
    if (r.equalsIgnoreCase("v")) {
        viewFile();
    }
    else if (r.equalsIgnoreCase("c")) {
        createWord();
    }
}


public static void createWord() throws FileNotFoundException {
    System.out.println("Input file name: ");
    Scanner viewFile = new Scanner(System.in);
    String toRead = viewFile.nextLine();
    File f = new File(toRead);
    while (!f.exists()) {
        System.out.println("File Not Found. Try again: ");
        toRead = viewFile.nextLine();
        f = new File(toRead);
    }
    Scanner input1 = new Scanner(new File(toRead));
    String input2 = input1;
    PrintStream output = new PrintStream(new File(toRead));
    while (input1.hasNext()) {
        String input = input1.next();
        for (int i = 0; i < input2.length(); i++) {
            if (input.startsWith("<") && input.endsWith(">")) {
                String token = input.substring(1, input.length() - 1);
                System.out.println("Please input a: " + token);
                Scanner scan = new Scanner(System.in);
                String replacement = scan.nextLine();
                token = token.replace(token, replacement);
                output.print(token);
            }
        }
    }
}


public static void viewFile() throws FileNotFoundException {
    System.out.println("Input file name: ");
    Scanner viewFile = new Scanner(System.in);
    String toRead = viewFile.nextLine();
    File f = new File(toRead);
    while (!f.exists()) {
        System.out.println("File Not Found. Try again: ");
        toRead = viewFile.nextLine();
        f = new File(toRead);
    }
    Scanner input1 = new Scanner(new File(toRead));
    System.out.println();
    while (input1.hasNextLine()) {
        System.out.println(input1.nextLine());
       }
    }
 }

非常感谢您的帮助。

0 个答案:

没有答案