0

我正在尝试制作一个允许用户创建文本文件并向其中添加单词列表的基本程序。当用户写“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!");




}

}
4

1 回答 1

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    
  }

您目前正在做的是比较参考资料。

于 2010-10-19T20:25:25.317 回答