LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-14-2018, 08:00 PM   #1
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 176

Rep: Reputation: 19
Java, while Loop Won't Break


Code:
            char choice = 'n';
            while (choice == 'n') {
                int[] stats = {0, 0, 0, 0, 0, 0};

                for (int i = 0; i < stats.length; i++) {
                    stats[i] = genStat();
                }

                System.out.println("Your stat rolls:");
                for (int i = 0; i < stats.length - 1; i++) {
                    System.out.print(stats[i] + ", ");
                }
                System.out.println(stats[stats.length - 1]);

                System.out.println("Do you want to keep these? (y or n)");
                
                char ans = in.next().charAt(0);
                if (ans == 'n' || ans == 'N') {
                    choice = 'n';
                }
                else if (ans =='y' || ans == 'Y') {
                    choice = 'y';
                }
                else {
                    System.out.println("Try again.");
                    choice = 'n';
                }
            }
As you can see, if choice stays 'n' or 'N' the loop continues. When the user answers 'y' or 'Y' it should break. It just keeps looping.

Can you tell me what I am missing?

Thanks,
Doug
 
Old 04-14-2018, 09:33 PM   #2
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: MID-SOUTH USA
Distribution: Slackware 14.2 / Slackware 14.2 current / Manjaro
Posts: 6,402

Rep: Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239
its not java but close. Its just converted into C, and I changed some of it, that part that was hanging you up, this is working C code. I checked it.

the same should work in Java as well. give it a try and let me know if it worked for you. you should be able to test this, yes?
Code:
#include <stdio.h>
#include <ctype.h>
 
int main (void)
{
char choice = 'n';

    while (tolower(choice) == 'n') 
    {
        int stats[] = {0, 0, 0, 0, 0, 0};

        for (int i = 0; i < 6; i++) 
        {
            //stats[i] = genStat();
            stats[i] = i;
        }

        //System.out.println("Your stat rolls:");
        printf("Your stat rolls:\n");
        
        
        for (int i = 0; i < 6; i++)
        {
            //System.out.print(stats[i] + ", ");
            printf("%d,", stats[i]);
        }
        //System.out.println(stats[stats.length - 1]);
            
        //System.out.println("Do you want to keep these? (y or n)");
          printf("Do you want to keep these? (y or n)\n");
          scanf(" %c", &choice);
          
          // can you not just use the same in Java with your choice?
          // like this. It will save you some coding
          
          //choice = in.next().charAt(0);
          
          if ( tolower(choice) == 'n' )
            printf("Try again\n");
             //System.out.println("Try again.");
          
          /*
                char ans = in.next().charAt(0);
                if (ans == 'n' || ans == 'N') {
                    choice = 'n';
                }
                else if (ans =='y' || ans == 'Y') {
                    choice = 'y';
                }
                else {
                    System.out.println("Try again.");
                    choice = 'n';
                }
                */
                
    } // end while
return 0;
}

Last edited by BW-userx; 04-14-2018 at 10:55 PM.
 
Old 04-15-2018, 08:35 AM   #3
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 176

Original Poster
Rep: Reputation: 19
I've made it a bit more succinct. (I had to figure out how toLowerCase worked on char variables in Java.) However, I still am unable to figure out what is preventing my loop from exiting. I'm trying to compare my code with yours, but I'm not seeing it.

Code:
       while (choice == 'n') {
            char answer = 'n';
            while (Character.toLowerCase(answer) == 'n') {
                int[] stats = {0, 0, 0, 0, 0, 0};

                for (int i = 0; i < stats.length; i++) {
                    stats[i] = genStat();
                }

                System.out.println("Your stat rolls are:");
                for (int i = 0; i < stats.length - 1; i++) {
                    System.out.print(stats[i] + ", ");
                }
                System.out.println(stats[stats.length - 1]);
                System.out.print("Do you want to keep them? (y or n)");
                answer = in.next().charAt(0);
            }
        }
 
Old 04-15-2018, 10:47 AM   #4
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,355

Rep: Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509
Try adding a bit of tracing:

Code:
String reply = in.next();
System.err.println("User replied:{"+reply+"}\n");
answer = reply.charAt(0);
You'll probably find there is some unexpected whitespace in the reply, or something like that.


Although in your latest post, it looks like the problem is that you never update choice.
 
Old 04-15-2018, 10:57 AM   #5
scasey
Senior Member
 
Registered: Feb 2013
Location: Tucson, AZ, USA
Distribution: CentOS 7.4
Posts: 1,260

Rep: Reputation: 441Reputation: 441Reputation: 441Reputation: 441Reputation: 441
From the OP:
Code:
else if (ans =='y' || ans == 'Y') {
Does the lack of a space between the == and the 'y' matter in Java? Just a WAG...
 
Old 04-15-2018, 11:15 AM   #6
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,355

Rep: Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509Reputation: 1509
Quote:
Originally Posted by scasey View Post
Does the lack of a space between the == and the 'y' matter in Java?
Nope.
 
Old 04-15-2018, 02:02 PM   #7
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: MID-SOUTH USA
Distribution: Slackware 14.2 / Slackware 14.2 current / Manjaro
Posts: 6,402

Rep: Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239
Quote:
Originally Posted by killingthemonkey View Post
I've made it a bit more succinct. (I had to figure out how toLowerCase worked on char variables in Java.) However, I still am unable to figure out what is preventing my loop from exiting. I'm trying to compare my code with yours, but I'm not seeing it.

Code:
   // the var named choice is what is being checked here
//       while (choice == 'n') {
            char answer = 'n';
            while (Character.toLowerCase(answer) == 'n') {
                int[] stats = {0, 0, 0, 0, 0, 0};

                for (int i = 0; i < stats.length; i++) {
                    stats[i] = genStat();
                }

                System.out.println("Your stat rolls are:");
                for (int i = 0; i < stats.length - 1; i++) {
                    System.out.print(stats[i] + ", ");
                }
                System.out.println(stats[stats.length - 1]);
                System.out.print("Do you want to keep them? (y or n)");
                // now you're using the var named anwser here, there is no
                 // way for the while ( condistion ) to be checked 
                 // against the var, answer.
                answer = in.next().charAt(0);
                 // should try
                choice = in.next().charAt(0);
            }
  }
Because as soon as choice no longer equals 'n' then it fails.
I put my comments in your code above.

you only need one while loop to control your code flow.
Code:
   import java.util.Scanner;
   
    public class MyFirstJava
    {
        public static void main(String[] args) 
    
        {
            Scanner c = new Scanner(System.in);
            char choice = 'n';
            while (Character.toLowerCase(choice) == 'n') 
            {
                
              for loop

              for loop

              for loop

              System.out.print("Do you want to keep them? (y or n)");
                
                // now you're using the var named answer here, there is no
                 // way for the while ( condition ) to be checked 
                 // against the var, answer.
               
                choice = c.next().charAt(0);
                 
            }
  }
    
    }

Last edited by BW-userx; 04-15-2018 at 03:12 PM.
 
Old 04-17-2018, 09:48 AM   #8
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 176

Original Poster
Rep: Reputation: 19
Quote:
Originally Posted by ntubski View Post
you never update choice.
Quote:
Originally Posted by BW-userx View Post
you only need one while loop to control your code flow.
These were the money quotes. I was thinking too far ahead. I was ending the inner loop, but the outer loop kept looping.

I'm writing a character generator for a role-playing game, because that hasn't been done before... (OK, sarcasm off.) The outside loop is going to be for whether or not the user likes the end product, or would like to start again.

So, taking your advice, I've removed the outer loop altogether and hey, it works. Thanks for the assist.

I've also added a method to clear the screen. If it seems a bit advanced for me... Yes, I stole it.

Code:
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class TravChar {
    public static int randSix() {
        Random rand = new Random();
        int randSix = rand.nextInt(6) + 1;

        return randSix;
    }

    public static int genStat() {
        int stat = randSix() + randSix();

        return stat;
    }

    public static void clrscr() {
        // Clears the screen in Java
        try {
            if (System.getProperty("os.name").contains("Windows")) {
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            }
            else {
                Runtime.getRuntime().exec("clear");
            }
        } catch (IOException | InterruptedException ex) {}
    }

    public static void main(String[] args) {

        String name;
        int str, dex, end, intel, edu, soc;
        Scanner in = new Scanner(System.in);

        char choice = 'n';
        while (choice == 'n') {
            int[] stats = {0, 0, 0, 0, 0, 0};

            for (int i = 0; i < stats.length; i++) {
                stats[i] = genStat();
            }

            Arrays.sort(stats);
            System.out.println("Your stat rolls are:");
            for (int i = 0; i < stats.length - 1; i++) {
                System.out.print(stats[i] + ", ");
            }
            System.out.println(stats[stats.length - 1]);
            System.out.print("Do you want to keep them? (y or n)");
            choice = in.next().charAt(0);
        }

        clrscr();
    }
}

Last edited by killingthemonkey; 04-17-2018 at 09:50 AM.
 
Old 04-17-2018, 09:52 AM   #9
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: MID-SOUTH USA
Distribution: Slackware 14.2 / Slackware 14.2 current / Manjaro
Posts: 6,402

Rep: Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239Reputation: 1239
Quote:
Originally Posted by killingthemonkey View Post
These were the money quotes. I was thinking too far ahead. I was ending the inner loop, but the outer loop kept looping.

I'm writing a character generator for a role-playing game, because that hasn't been done before... (OK, sarcasm off.) The outside loop is going to be for whether or not the user likes the end product, or would like to start again.

So, taking your advice, I've removed the outer loop altogether and hey, it works. Thanks, for the assist.

I've also added a method to clear the screen.
maybe read up on loop nesting. your outer loop is your (overall) control loop for the processing of the code within that loop (and the other loops inside of it.) along with break and continue. They are very helpful when used properly, if needed.

It's good to see you're figuring it out.

Last edited by BW-userx; 04-17-2018 at 09:56 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] Java, Do-While Loop, Loop Won't Break When Cnodition is Met killingthemonkey Programming 2 06-16-2017 12:42 PM
break out oa while loop once size condition is met casperdaghost Linux - Newbie 6 02-24-2012 01:11 AM
How to break if loop in Perl? Barca Programming 9 08-03-2011 01:15 PM
break while [...] loop when a program finishes throughthegreens Linux - Newbie 6 02-18-2010 11:12 AM
break loop in C++ marek Programming 10 09-11-2003 10:59 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:59 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration