Search code examples
javanested-loops

Having issues with printing a nested loop


I am trying to print a nested loop that will print two islands and scale depending on what the input is. The goal is to make Exclamation points(!) to make the left island, a line diagonally of asterisks(*), question marks to make the right island and tildas(~) to make the ocean. Any comments on my code would be helpful.

Example of what I am trying to do.

Input a size (must be larger than 1):
5

0 !!~~*
1 !!~*~
2 ~~*~~
3 ~*~??
4 *~~??

Here is my code:

import java.util.Scanner;
public class Two_Islands {
    public static void main(String[] args) {
        Scanner kbinput = new Scanner(System.in);
        //Create Size variable
        System.out.println("Input a size: ");
        int n = 0; n = kbinput.nextInt();

        for (int r = 0; r < n; r++) {
            System.out.print(r);
            for (int c = 0; c < n; c++) {
                if (r+c == n-1) {
                    System.out.print("*");
                } else if (r+c == n-2) {
                    System.out.print("!");
                } else if (r+c == n+2) {
                    System.out.print("?");
                } else {
                    System.out.print("~");
                }
            }
            System.out.println();
        }
        kbinput.close();
    }
}

Here is my current output.

Input a size: 
5
0~~~!*
1~~!*~
2~!*~~
3!*~~?
4*~~?~

Solution

  • try the following:

    else if(r+1 < n/2 && c+1 < n/2)
    {
        System.out.print("!");
    }
    else if(r+1 > n-n/2 && c+1 > n-n/2)
    {
        System.out.print("?");
    }