用于关闭 FileWriter 的哨兵值 (Java)
我正在尝试制作一个基本程序,允许用户创建文本文件并向其中添加单词列表。当用户写入“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!");
}
}
I'm trying to make a basic program that allows a user to create a text file and add a list of words to it. When the user writes "stopnow" - the file should close. Unfortunately, right now it's just an infinite loop. What am I doing wrong:
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!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要检查字符串是否相等,请使用
.equals
您当前正在做的是比较引用。
To check for String equality, use
.equals
What you are currently doing is comparing references.