views:

8

answers:

1

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




}

}
+2  A: 

To check for String equality, use .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    
  }

What you are currently doing is comparing references.

Amir Afghani
Everyone must be out to lunch if no ones answered this but me by now...
Amir Afghani
so, the != operator is only for int's?
Woops4000
I was about to answer it, but then a coworker stopped by to ask me a question. Stupid work getting in the way of SO.
jjnguy
@Woops, `!=` is only for primitive types like `int`, `double`, `char` and so on.
jjnguy