Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use while loop that represents split() and also for loop to display selection number for user?

For loop inside While loop not executing at all.
It would work fine without the for loop but had to add the for loop in order to have selection numbers displayed on the screen.(e.g. 1.2.3)


try
{
    BufferedReader br = new BufferedReader(new FileReader(path));
    while((line = br.readLine()) != null) {
        String[] values = line.split(",");
        for (int i = 0; i < zoo.size(); i++) {
            System.out.println("Select your choice.\nPress" + (i + 1) + ". (4Legged): " + values[0] + ", (insect):" + values[1] + ", (bird): " + values[2] );
        }
    }

The txt file example is:

Monkey, Ant, Crow
Cat, Spider, Chicken
Dog, Grasshopper, Magpie

The desired output is:
Select your choice.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Press 1. (4Legged): Monkey, (Insect): Ant, (Bird): Crow

Press 2. (4Legged): Cat, (Insect): Spider, (Bird): Chicken

Press 3. (4Legged): Dog, (Insect): Grasshopper, (Bird): Magpie

>Solution :

try
{
BufferedReader br = new BufferedReader(new FileReader(path));
int index = 1;
while((line = br.readLine()) != null) {
    String[] values = line.split(",");
    
        System.out.println("Select your choice.\nPress" + index + ". (4Legged): " + values[0] + ", (insect):" + values[1] + ", (bird): " + values[2] );
    index ++;
}

just use a flag before while loop and use that in your print statement and increment it after printing the values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading