Java Rectangle Patterns Write a program that reads in lines from the input. Each
ID: 3811033 • Letter: J
Question
Java
Rectangle Patterns
Write a program that reads in lines from the input. Each line has two integer values followed by a single character. The objective is to print a rectangle pattern using the input pattern. The first integer represents the number of rows and the second integer represents the number of columns.
Input
The format of an input line is noRows noCols char The first two are integers (and can be read using nextInt()). The last one is a single character (like *) and can be read using next() as a String and then using charAt(0) to get at the first character.
Output
For each line of input, a rectangular pattern is printed consisting of several rows. If the no of rows or cols is less than or equal to zero or more than 50, the program prints out an error statement as shown in the sample output.
Sample Input
2 2 ,
2 51 +
10 10 =
0 11 *
Sample Output
,, ,,
error in input
==========
==========
==========
==========
==========
==========
==========
==========
==========
==========
error in input
HINT
1. use in.next().charAt(0) to get the character.
2. don’t forget to discard the rest of the input line using in.nextLine() if you are using in.hasNextLine() to check if there is a next line.
3. You will need TWO loops to print each rectangle.
Thank you!
Explanation / Answer
RectanglePatterns.java
import java.util.Scanner;
public class RectanglePatterns {
public static void main(String[] args) {
//Declaring variables
int rows,cols;
char ch,choice;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//this loop continues to execute until the user enters 'y' or 'Y'
do
{
//Getting the input entered by the user
System.out.println(" Enter input :");
rows=sc.nextInt();
cols=sc.nextInt();
ch=sc.next(".").charAt(0);
//if the user entered invalid input then dislay error message
if(rows<=0 || cols>=50)
System.out.println("error in input");
else
{
//for valid input display pattern
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=cols;j++)
{
System.out.print(ch);
}
System.out.println();
}
}
//Getting the character from the user 'Y' or 'y' or 'N' or 'n'
System.out.print("Do you want to continue(Y/N) ::");
choice = sc.next(".").charAt(0);
}while(choice=='y' || choice=='Y');
}
}
____________________
Output:
Enter input :
2 2 ,
,,
,,
Do you want to continue(Y/N) ::y
Enter input :
2 51 +
error in input
Do you want to continue(Y/N) ::y
Enter input :
10 10 =
==========
==========
==========
==========
==========
==========
==========
==========
==========
==========
Do you want to continue(Y/N) ::y
Enter input :
0 11 *
error in input
Do you want to continue(Y/N) ::n
______________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.