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

Java output lines with each lines containing two string

I want to outpot the N lines with each lines containing either Mary or Jobert. I only know how to loop it but I don’t know how it would stop based on the N number

import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
      
      int n= 5;
      
    for (int i = 1; i <= 5; i++) {
      for (int j = 1; j < i; j++) {
      
        System.out.println("Mary ");
       
      }
       for (int k = 1; k < i; k++) {
          System.out.println("Jobert");
       
      }

    }
    }
}

The output is

Mary 
Jobert
Mary 
Mary 
Jobert
Jobert
Mary 
Mary 
Mary 
Jobert
Jobert
Jobert
Mary 
Mary 
Mary 
Mary 
Jobert
Jobert
Jobert
Jobert

but what I want is that it would stop at 5 words since n is 5

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

Mary 
Jobert
Mary 
Mary 
Jobert

>Solution :

Try below code :

class Test {
    public static void main(String[] args) {
      
        int n = 7;
        int counter = 0;
      
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j < i; j++) {
                if(j > 1) {
                    counter++;
                    System.out.println("Mary ");
                }
                
                if(counter == n) {
                    break;
                }
            }
       
            for (int k = 1; k < i; k++) {
                if(k > 1) {
                    counter++;
                    System.out.println("Mary ");
                }
                
                if(counter == n) {
                    break;
                }
            }
        }
    }
}
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