Results 1 to 3 of 3
Like Tree3Likes
  • 2 Post By Junky
  • 1 Post By xlomo

Thread: Problem with while loop, assigning a variable with a different value every loop? Help

  1. #1
    JavaProg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Problem with while loop, assigning a variable with a different value every loop? Help

    Hey, this is a simple tester program I tried to put together. Only problem is that once a value is given for "counter", this value doesn't seem to change itself afterwards, despite the while loop.

    Here it is anyway:

    import java.util.Scanner;

    class tut {
    public static void main(String args []){
    Scanner scan = new Scanner(System.in);
    System.out.println("Would you like me to ask this question again? ");
    String counter = scan.nextLine();
    while(counter.equals("yes")){
    main(args);



    }
    }
    }

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Problem with while loop, assigning a variable with a different value every loop?

    I highly recommend NOT calling the main method from within your program. If you want the code repeating while user enters "yes" then use a do while loop instead and place the line asking the question and the line getting user input inside the loop. Also I would use equalsIgnoreCase to handle "YES", "Yes" etc.
    Fubarable and JeffGrigg like this.

  3. #3
    xlomo is offline Member
    Join Date
    Dec 2010
    Posts
    19
    Rep Power
    0

    Default Re: Problem with while loop, assigning a variable with a different value every loop?

    have in mind that in this code you will need to give as many "yes" as the count of any other reply in order to terminate. Keep giving yes and it will terminate.
    The reason is that every time you type something else a new main is called and so one more yes is needed in order to end.
    Fubarable likes this.

Similar Threads

  1. multiply variable in for loop
    By aconti in forum New To Java
    Replies: 7
    Last Post: 06-03-2011, 12:24 PM
  2. Accessing a variable from a loop
    By mhz041986 in forum New To Java
    Replies: 4
    Last Post: 04-04-2011, 08:49 AM
  3. Variable not initialized after while loop
    By ejs7597 in forum New To Java
    Replies: 6
    Last Post: 02-28-2009, 05:00 AM
  4. Replies: 3
    Last Post: 11-24-2008, 07:01 PM
  5. [SOLVED] Referencing Variable within Loop
    By Judoon_Platoon in forum Java Applets
    Replies: 2
    Last Post: 05-22-2008, 11:54 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •