有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:需要在单行上替换不同的字符串类型,然后打印到txt文件

我知道这是一个java初学者的问题,但我需要阅读一个madlib文件,其中需要替换的单词介于两者之间<>;,即。然后,它会提示用户输入相同类型的单词,我几乎已经完成了,除了出现“<;”之外废话“>;”两个在同一条线上,在同一条线上。我可能只需要一个局外人的观点来指出显而易见的事情,但我无法理解。我知道ArrayList是完美的,但我只能使用扫描仪、PrintStreams和简单数组。以下是迄今为止我对该方法的了解:

public static void readFilePrint(Scanner console, File fileIn) throws    
       FileNotFoundException {
  PrintStream stream = new PrintStream(new File("out1.txt"));
  Scanner fileScan = new Scanner(fileIn);   
  String line = "";
  String temp = "";
  String token = "";
  int count = 0;

  String toRep = "";
  boolean multiple = false;
while (fileScan.hasNextLine()) { 
  line = fileScan.nextLine();
  String tempo = line;
  Scanner lineScan = new Scanner(line);  
  while (lineScan.hasNext()) { 

     token = lineScan.next();

     if (token.charAt(0) =='<') {

        String type = toRep.substring(1, token.length() - 1);
        System.out.print("Please type a/an " + type + ":"); 
        //word to replace toRep (same as token)
        String word = console.next();

        line = line.replace(token, word);
        toRep = token.substring(0, token.length() - 1);   
        toRep = line.replace(token, word);         
        temp  =  toRep;
        count++;
        if (count >= 1) {
          toRep +=  " " + temp;
        }
      }
      count = 0;

   }   

}

这是我唯一需要帮助的方法,它写得非常完美。我对变量的混乱感到抱歉;有时我创建变量来测试不同的想法来解决问题,注释出原始代码,然后忘记。我知道我只是在放屁,因为有那么多更好的东西可以完成这个任务。我已经很长时间没有使用像这样的硬编码了,所以非常感谢您的帮助


共 (0) 个答案