Sentinel值关闭FileWriter(Java)

时间:2010-10-19 20:22:26

标签: java printwriter

我正在尝试制作一个基本程序,允许用户创建文本文件并为其添加单词列表。当用户写“stopnow”时 - 该文件应该关闭。不幸的是,现在它只是一个无限循环。我做错了什么:

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


    public class WordList 
    {
 public static void main(String[] args) throws IOException
 {
  System.out.println("What would you like to call your file? (include extension)");

  Scanner kb = new Scanner(System.in); // Create Scanner

  String fileName = kb.nextLine(); // assign fileName to name of file

  PrintWriter outputFile = new PrintWriter(fileName); // Create the file

  String input;

  System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word

  input = kb.nextLine(); // assign input as the word

  while (input != "stopnow")

  {
   outputFile.println(input); // print input to the file

   System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word

   input = kb.nextLine(); // assign input as the word

  } 

  outputFile.close(); //Close the File

  System.out.println("done!");




}

}

1 个答案:

答案 0 :(得分:2)

要检查字符串相等性,请使用.equals

 while (!input.equals("stopnow"))    
  {
   outputFile.println(input); // print input to the file    
   System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word
   input = kb.nextLine(); // assign input as the word    
  }

您目前正在做的是比较参考文献。