2010-10-19 28 views
0

我试图做一个基本的程序,允许用户创建一个文本文件并添加一个单词列表。当用户写入“停止”时 - 文件应该关闭。不幸的是,现在它只是一个无限循环。我在做什么错:Sentinel值关闭FileWriter(Java)

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!"); 




} 

} 
+0

不是这样。多少次必须*相同*这个问题应该回答? – 2010-10-20 00:06:17

回答

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  
    } 

什么目前你正在做的是比较引用。

+0

如果现在没有人回答这个问题,我现在每个人都应该出去吃午饭... – 2010-10-19 20:27:59

+0

所以,!=运算符只适用于int的吗? – Woops4000 2010-10-19 20:28:50

+0

我正准备回答,但随后一位同事停下来问我一个问题。愚蠢的工作妨碍了SO。 – jjnguy 2010-10-19 20:29:20