gpt4 book ai didi

java - 用于关闭 FileWriter 的哨兵值 (Java)

转载 作者:行者123 更新时间:2023-12-02 08:28:33 26 4
gpt4 key购买 nike

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

您当前正在做的是比较引用文献。

关于java - 用于关闭 FileWriter 的哨兵值 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3972415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com