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




}

}
有帮助吗?

解决方案

要检查字符串平等,请使用 .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    
  }

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top