I am trying to write a program that will ask the user for a size of a square and then print out a square that has that many *'s.
For example,
Size?
3
Then it prints out a 3 x 3 square of *'s.
I need to also use for and while loops.
Thanks
Working code :
import java.util.Scanner;
public class patternBox {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter number of row / column : ");
int row = input.nextInt(); // take user input
for (int i = 0; i < row; i++) { // outer loop for row change
for (int j = 0; j < row; j++) // inner loop for * print
{
System.out.print("*");
}
System.out.println();
}
}
}
Read: How to get input from user using Scanner
Related
I am writing a code to indicate open and closed elements in a 2d array. An open element is represented with . and a closed element is represented with *. The first column in the array must be completely open whereas all the other columns must be closed. The output should be:
.**
.**
.**
The array is also going to vary in size as the user will determine how big the array is. I have managed to code a 2D array grid as this is not hard, however, I am trying to now use an if-statement to make the first column all open. I placed the if-statement within the nested loop:
import java.util.Arrays;
import java.util.Scanner;
public class trial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
grid[i][j] ='.';
if(grid[j].length > grid[0].length) {
System.out.println("");
}else {
System.out.print('*');
}
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
This, however, is giving me an output that looks like this:
*.*.*.
*.*.*.
*.*.*.
*.*.*.
I have tried placing the if-statement outside of this nested for-loop but I then get an error with my variables as they have not been defined. Any assistance as to how to fix this or make it that I can get values for my i and j variables outside of the for-loop would be greatly appreciated.
I slightly modify your code to make it fit the description.
i and j will vary when the loop proceeds, and should be accessed inside the loop only.
It seems that you want to change the content inside grid, which can be accessed outside the loop after processing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
grid[i][j] = '.';
if(j > 0) {
grid[i][j] = '*';
}
System.out.print(grid[i][j]);
}
System.out.println();
}
// you cannot access i/j outside the loop scope. instead, you can access the grid
System.out.println("Loaded array:");
Arrays.stream(grid).forEach(System.out::println);
}
Just check if the current column is 0 or not
Just a minor change will work here
I am writing only the main loop below
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
if(j == 0){ //0th column make it dot(.)
grid[i][j] ='.';
}
else { //For other columns put asterisk(*)
grid[i][j] = '*';
}
}
}
Here's a different way to think about 2D arrays. They are simply a 1D array where each element is itself another 1D array (a complete "row").
With that in mind, here's a different way to initialize and print the contents of the 2D array using a mixture of enhanced and indexed for loops:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
for(char[] row : grid) {
for(int col=0; col<row.length; col++) {
row[col] = (col == 0) ? '.' : '*';
}
}
for(char[] row : grid) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
Output:
What size square grid do you want?
5
.****
.****
.****
.****
.****
I just learned how to use nested loops today and the task I am required to do is quite simple but I am not able to execute it properly, although with the same idea.
The task is to input a character, an integer that is the rows**(n), and another integer that is the columns **(m)
It should display the rectangular pattern with n rows and m columns
Sample input:
*
3
2
Here the number of rows is 3 and the number of columns is 2
Sample output:
**
**
**
This has to be done using nested for loops only
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = m; x <= m; x++) {
for (int y =n ; y <= n; y++) {
System.out.print(character);
}
System.out.println("");
}
}
}
The output I am getting:
*
You should use a loop like this start from 0 to row and j from 0 to col for each row, and close the scanner after reading
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int col = keyboard.nextInt();
int row = keyboard.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(character);
}
System.out.println("");
}
keyboard.close();
}
, output
***
***
You should start from 0 in both loops until reaching < m and < n as follows:
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = 0; x < m; x++){
for (int y = 0; y < n; y++){
System.out.print(character);
}
System.out.println("");
}
A sample input/output would be:
*
3
2
***
***
what is wrong in your code is that you are starting loop from m itself instead you should think it like how many times you want to run the loop.
With that in mind try running the code from 0 to m and inner loop from 0 to n.
This mindset will help you in learning while loop also.
import java.util.Scanner;
class Example {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = 0;x<m;x++){
for (int y=0;y<n;y++){
System.out.print(character);
}
System.out.println("");
}
}
}
My program will output a graphical representation of some rows and columns. It asks the users to input the number of rows and columns they want to see the figure for. For example if the user chooses 4 rows and 3 columns, it should print a figure (let's say it's made up of character X) which has 4 rows and 3 columns.
The final output will look like this:
X X X
X X X
X X X
X X X
Now the problem is I can't set the logic in my for loop so that it makes the desired shape. I tried, but couldn't figure it out.
This what I have done so far:
package banktransport;
import java.util.*;
public class BankTransport {
static int NumOfRow;
static int numOfColum;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
showRowCol(NumOfRow, numOfColum);
}
public static void showRowCol(int NumOfRow, int numOfColum) {
System.out.println("Enter row: ");
NumOfRow = input.nextInt();
System.out.println("Enter Col: ");
numOfColum = input.nextInt();
System.out.println("");
System.out.println("Visual Representation: ");
//print column and row
for (int i = 0; i < numOfColum; i++) {
System.out.print(" X ");
//System.out.println("");
//for(int j=1; j<(NumOfRow-1);j++){
// System.out.print(" Y ");
//}
}
System.out.println("");
}
}
Try a loop like this:
for ( int i = 0; i < numOfRow; i++ )
{
for ( int j = 0; j < numOfColum; j++ )
{
System.out.print(" X ");
}
System.out.println();
}
Try:
for (int i = 0; i < numOfRow; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < numOfColumn; j++) {
line.append("X ");
}
System.out.println(line.toString());
}
You can also use Apache Commons Lang StringUtils.repeat method (which would prevent you from having a trailing space at the end of the line):
for (int i = 0; i < numOfRow; i++) {
System.out.println(StringUtils.repeat("X", " ", numOfColumn));
}
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
// For you to test
//int[][] testArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] testArray = {
{ randomNumber(), randomNumber(), randomNumber() },
{ randomNumber(), randomNumber(), randomNumber() },
{ randomNumber(), randomNumber(), randomNumber() } };
//
// TO DISPLAY ARRAY
printArray(testArray);
} // end main
// TO DISPLAY TABLES
private static void printArray(int[][] array) {
Scanner sc = new Scanner(System.in);
//Ask the user
System.out.println("How many rows: ");
int rows= sc.nextInt();
System.out.println("How many columns: ");
int columns= sc.nextInt();
for (int row = 0; row < array.length; rows++) {
for (int col = 0; col < array[rows].length; col++) {
System.out.print(array[rows][columns] + " ");
}
System.out.println();
}
}
private static int randomNumber() {
int random = (int) (Math.random() * 9);
return random;
}
}
Currently my program is working only with three rows and three columns. How can I make work so that it works with any rows and columns the user inserts?. And then my methods work with whatever the user insert?
To use a user inputted size, you can do the same thing you're doing in printArray() and then use those sizes to create the array:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask array size to the user
System.out.println("How many rows: ");
int rows= sc.nextInt();
System.out.println("How many columns: ");
int columns= sc.nextInt();
// Fill array with random numbers
int[][] testArray = new int[rows][columns];
for (int i=0; i<testArray.length; ++i) {
for (int j=0; j<testArray[i].length; ++j) {
testArray[i][j] = randomNumber();
}
}
// TO DISPLAY ARRAY
printArray(testArray);
} // end main
Also, you're using the array length instead of the current element when walking it:
This looks incorrect
for (int row = 0; row < array.length; rows++) {
for (int col = 0; col < array[rows].length; col++) {
System.out.print(array[rows][columns] + " ");
}
System.out.println();
}
Fix (note how rows and columns were replaced in the outer for and in the print()):
for (int row = 0; row < columns; row++) {
for (int col = 0; col < rows; col++) {
System.out.print(array[row][col] + " ");
}
System.out.println();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ClassName {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader( new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
int b = Integer.parseInt(reader.readLine());
//testArray will be axb dimensions.. depending on what user inputed
int[][] testArray = new int[a][b];
}
}
You can use scanner for user input as well. If you're learning java perhaps it's even easier to use Scanner. If you want or need to use BufferedReader and don't understand what "throws IOException" does, refer to this link: http://docs.oracle.com/javase/tutorial/essential/exceptions/
If you're in a hurry to implement this code just keep putting "throws IOException" on every method that uses .readLine() and read upon exceptions later.
I prefer to use BufferedReader because Scanner, in my experience, has been known to go crazy if you use it in a loop.
This question already has answers here:
How to print Two-Dimensional Array like table
(16 answers)
Closed 9 years ago.
I'd like to print an inputed 2-dimensional array like a table
i.e if for some reason they put in all 1s...
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Just like so above but in the console on Java eclipse, no fancy buttons and GUI's but in the console, here is what I have....
import java.util.Scanner;
public class Client {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i=0; i < table.length; i++) {
for (int j=0; j < table.length; j++) {
System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println(table);
}
}
And this is what I get when I input everything and the console terminates:
Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1
[[I#3fa1732d
Consider using java.util.Arrays.
There is a method in there called deepToString. This will work great here.
System.out.println(Arrays.deepToString(table));
Relevant here: Simplest way to print an array in Java
You need to print out the array separately from entering the number. So you can do something like this:
public class PrintArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
// System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
}
//System.out.println();
}
// System.out.println(table);
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
You'll have loop back through those arrays to print out the contents. an array's toString() just prints the reference value.
System.out.print(table) calls a method in array class that prints out the identifier of the vairable. you need to either create a for loop that will print out each element like System.out.print(table[i][j]) or use the Arrays class and say Arrays.toString(table);
Try copying this simple for loop to printing a 4x4 table:
Scanner input = new Scanner();
int numArray [] [] = new int [4] [4];
for ( int c = 0; c < 4; c++ ) {
for (int d = 0; d < 4; d++) {
System.out.print("Enter number : ");
nunArray [c][d] = input.nextInt();
}
}
for (int a = 1; a<5;a++) {
for (int b = 1; b <5;b++) {
System.out.print(numArray [a][b]+" ");
}
System.out.println();
}