0

So I have most of my code written, but there's one part of the assignment that I don't understand. Write a program that will accept a number (n) from the user to represent the size of a board (nxn). If the user does not enter a number greater than 1, prompt the user over and over until he/she gives valid input.

Once valid input is obtained, print a board with every other column filled with 1s along with the last row filled with 1s. Zeros everywhere else. Your board will have an equal number of rows and columns based on the users input.

I have it to do the pattern with the 0's and 1's but I don't understand how I can get the last row to have all 1's. Here is my code posted below

import java.util.Scanner;
public class question1 {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Please input a value for the board greater than 1.");
n= input.nextInt();
while(n<1)
{
    System.out.println("Error, please enter a value greater than 1");
    n=input.nextInt();
}
for(int i=0; i<n; i++)
{
    for(int j=0; j<n; j++)
    {

        if(j%2==0)
        {
            System.out.print(0);
        }
        else
        {
            System.out.print(1);
        }
        if(i==n)
        {
            System.out.print(1);
        }


    }
    System.out.println(' ');
}
}
}
1
  • Minor adjustment: instead of while(n<1) you should use while(n<=1) Commented Nov 13, 2014 at 2:38

2 Answers 2

2

Change your loops to:

for (int i = 0; i < n; i++) {
  for (int j = 0; j < n; j++) {
    if (i == n - 1) {
      System.out.print(1);
    } else {
      System.out.print(j % 2);
    }
  }
  System.out.println();
}
Sign up to request clarification or add additional context in comments.

Comments

0
 if(i==n)
    {
        System.out.print(1);
    }

you should just change to (i == n-1)

3 Comments

This would print 2 * n characters in the last row.
That still won't quite do it, since he's already printed 0/1 by that time.
Agree, I missed that part. The answer below provides a better code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.