I'm building out a user defined array as a game board. The characters used "O" and "." have to be randomized and the "O" has to appear more than once.
This is what I have thus far.
import java.util.Scanner;
public class PacMan {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
boolean[][] cookies = new boolean[row+2][column+2];
for (int i = 1; i <= row; i++)
for (int j = 1; j <= column; j++);
cookies [row][column] = (Math.random() < 100);
// print game
for (int i = 1; i <= row; i++)
{
for (int j = 1; j <= column; j++)
if (cookies[i][j]) System.out.print(" O ");
else System.out.print(". ");
System.out.println();
}
}
}
The output, for example, produces a 5 x 5 grid, but the "O" only appears once and is at the bottom right of the grid.
Assistance randomizing the "O" and "." and having the "O" appear in random fashion throughout the board which is initialized by the user input via Scanner.
Here is the updated code which is producing the output that I'm looking for and is user defined.
import java.util.*;
public class PacManTest
{
public static void main(String[] args)
{
char O;
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
char board[][] = new char[row][column];
for(int x = 0; x < board.length; x++)
{
for(int i = 0; i < board.length; i++)
{
double random = Math.random();
if(random >.01 && random <=.10)
{
board[x][i] = 'O';
}
else {
board[x][i] = '.';
}
System.out.print(board[x][i] + " ");
}
System.out.println("");
}
}
}
The main issue is the typo in the first loop:
cookies [row][column] = (Math.random() < 100);
should be
cookies [i][j] = (Math.random() < 100);
Second, Math.random() returns a value greater than or equal to 0.0 and less than 1.0 (doc). So, (Math.random() < 100); will always be true. If you want a 50% chance of an O or . use:
cookies[i][j] = Math.random() < 0.5;
Also, not sure what your motivation is for using a starting index of 1 but array indexes start at 0.
Related
Help with this question:
Take a positive integer n and form n triangles from stars with their base down of size n each.
For example, for input 3, the following output will be obtained:
* * *
** ** **
*** *** ***
Here's what I've tried.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
for (int c = 1; c <= r; c++)
System.out.print("*");
System.out.println();
}
}
}
Here's my solution, with explanations in comments
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) { // <-- we will have to print n rows
printLine(n, r);
}
}
}
static void printLine(int n, int lineNumber) {
StringBuffer line = new StringBuffer();
for(int i = 0; i < n; i ++) { // <-- each line will have '*'s for n triangles
for(int j = lineNumber; j > 0; j--) { // <-- each line has as many '*'s as its line number, so print those first
line.append("*");
}
for(int j = 0; j < n - lineNumber + 1; j ++) { // <-- we then have to add enough spaces to leave room for the next triangle's '*'s
line.append(" ");
}
}
System.out.println(line.toString()); // <-- print the line we've built so far
}
}
EDIT:
Here's a replit that avoids one of the loops by using a modulo to print an entire line at once, and also uses recursion, for no real reason, in place of the outer-most loop: https://replit.com/#anqit/MicroExtrovertedTrace#Main.java
First, the blanks follow the stars, then, you have to repeat n times the two loops:
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++)
System.out.print("*");
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
}
System.out.println();
}
You have one for loop that prints out a single triangle of stars using nested for loops. The outer loop is responsible for the number of rows and the inner loops are responsible for printing the spaces and stars.
In my updated code, I added an outer loop that runs n times, and each time it runs, it prints out a triangle of stars. The inner loops are responsible for printing the stars of the triangle and spaces between the triangles.
The main difference is that in your first code, only one triangle is printed, while in my updated code, n triangles are printed. In addition, the indentation of the inner loops has been adjusted to align the triangles correctly on the same line.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n:");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error: please enter a positive number:");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++) {
System.out.print("*");
}
for (int i = 0; i < n - r + 1; i++) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Here is a 3 forloop variant
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder b = new StringBuilder("");
for (int s = 0; s < n; s++) {
b.append(s < i ? "*" : " ");
}
String line = b.append(" ").toString();//space between
for (int j = 1; j < n; j++) {
System.out.print(line);
}
System.out.println();
}
produces
> * * *
> ** ** **
> *** *** ***
> **** **** ****
So far, my code is this one:
import java.util.Scanner;
public class PG1 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
//declaration,creation, initialization
double [][] matrix = new double [i][j];
//print element in row i
for (i = 0; i < matrix.length;i++){
//print element j in row i
for (j = 0; j < matrix[i].length; j++) {
System.out.print("The matrix is: " + matrix[i][j]);
}
System.out.println();
}
}
}
So basically, I want to print the 0s and 1s according to the user's input or row and column of the matrix. Your help will be much appreciated.
output:
Enter the length of the matrix: 4
The matrix:
0 1 1 1
0 0 0 0
0 1 0 0
1 1 1 1
All 0s on row 1
All 1s on row 3
No same numbers on a column
No same numbers on the diagona
you can achive like this:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0){
count0s++
System.out.print("The matrix is: " + matrix[i][j]);
}
else if(matrix[i][j] == 1){
count1s++
System.out.print("The matrix is: " + matrix[i][j]);
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}
}
If you dont want to print 0s and 1s :
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0)
count0s++
else if(matrix[i][j] == 1)
count1s++
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}
I can't seem to figure out how to get it to look for any of the random numbers in the array and check if they are divisible by the user input. It just gives me the constant result of
"Number of total divisible inputted numbers: (0)"
import java.util.Random;
import java.util.Scanner;
public class Divisor
{
public static void main (String []args)
{
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int[][]strings = new int [4][4];
for (int i = 0; i < strings.length;i++)
{
for(int j = 0; j < strings.length;j++)
{
System.out.println("Please enter the 16 numbers to be checked for division!");
strings[i][j]=keyboard.nextInt();
}
}
int count = 0;
for (int i = 0; i < strings.length;i++)
{
for(int j = 0; j < strings[i].length;j++)
{
strings[i][j] = 1 + (int)(Math.random()*100);
if (strings[i][j]%keyboard.nextInt()==0)
{
count++;
}
System.out.println("Number of total divisible inputted numbers: "+"("+count+")");
}
}
}
}
You may want something like this:
import java.util.Random;
import java.util.Scanner;
public class Divisor
{
public static void main (String []args)
{
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int[][]strings = new int [4][4];
int input = 0;
// ask the user for input
System.out.println("Please enter the 16 numbers to be checked for division!");
input=keyboard.nextInt();
// generate random numbers
for (int i = 0; i < strings.length;i++)
{
for(int j = 0; j < strings[i].length;j++)
{
strings[i][j] = 1 + rand.nextInt(100);
//System.out.println(strings[i][j]); // print what is created for testing
}
}
// count divisible numbers for each input
int count = 0;
for (int i = 0; i < strings.length; i++)
{
for (int j = 0; j < strings[i].length; j++)
{
if (input != 0 && strings[i][j] % input == 0) count++;
}
}
System.out.println("Number of total divisible inputted numbers: "+"("+count+")");
}
}
Do you know what your code is doing? Here is a short description:
Make the user input 16 numbers in a array.
System.out.println("Please enter the 16 numbers to be checked for division!");
strings[i][j]=keyboard.nextInt();
Overwrite each number with a random int by Random.nextInt().
strings[i][j] = rand.nextInt();
Compare if a new randomized number (not the same) is divisible by a number the user inputs.
if (rand.nextInt()%keyboard.nextInt()==0)
Do you see the problem?
public class Divisor
{
public static void main (String []args)
{
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int[][]strings = new int [4][4]; //Strange calling an array of ints for "strings".
for (int i = 0; i < strings.length;i++)
{
for(int j = 0; j < strings[i].length;j++)
{
strings[i][j] = rand.nextInt(); // Lets add some random number to a 4x4 array.
}
}
int count = 0;
int comparable = keyboard.nextInt(); // We are looking for this number.
for (int i = 0; i < strings.length;i++)
{
for(int j = 0; j < strings[i].length;j++)
{
if (strings[i][j] % comparable == 0) //Does the number match the one we are looking for?
{
count++;
System.out.println("Found a number!");
}
}
}
//We have now looked in the entire array
System.out.println("Number of total divisible inputted numbers: "+"("+count+")");
}
}
Except for an extra column produced by the code, everything works fine except my avg method which was meant to average the value in each row. I'm new to coding, so maybe I'm not seeing the problem, but the method isn't working as intended. At first I thought it was an issue with the sum but changing it didn't really resolve the initial problem. A column input of (2,1,3) will produce an exception error at 1 but does not occur when the input is (1,3,2). Also the avg is producing only 2 regardless of column length.
I'm aiming for the code to print this when column input of (1,2,3) is entered:
A:2.0 [1.0]
B:2.0 2.0 [2.0]
C:2.0 2.0 2.0 [3.0]
where the bracketed term is the average for that row.
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 0; row < figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
public static double avg(double temp[][]) {
int sum = 0;
int avg = 0;
for (int row = 0; row < temp.length; row++){
for (int col = 0; col < temp[col].length; col++)
sum += temp[row][col];
}
avg = sum / temp.length;
return avg;
}
}
I think what you are doing wrong is instead of summing up all elements of a row and taking average, you are summing up the whole matrix and taking average which will always be the same value.
This is not homework. I am a beginner (novice) java programmer, trying to read and complete the exercises at the end of ivor horton's beginning java book.
Write a program to create a rectangular array containing a multiplication table from 1 X 1 to 12 X 12. Output the table as 13 columns with the numeric values right aligned in columns. (The first line of output will be the column headings, the first column with no heading, then the numbers 1-12 for the remaining columns. The first item in each of the succeeding lines is the row heading which ranges from 1-12.
NOTE: I have only learned about Arrays & Strings, Loops & Logic, data types, variables, and calculations. I have not learned about classes and their methods and etc......so no fancy stuff please. THANKS!
public class Chapter4Exercise2 {
public static void main(String[] args)
{
int[][] table = new int[12][12];
for(int i=0; i <= table.length-1; i++)
{
for (int j=0; j <= table[0].length-1; j++)
{
table[i][j] = (i + 1) * (j + 1);
if (table[i][j] < 10)
System.out.print(" " + table[i][j] + " ");
else
if (table[i][j] > 10 && table[i][j] < 100)
System.out.print(" " + table[i][j] + " ");
else
System.out.print(table[i][j] + " ");
}
System.out.println(" ");
}
}
}
As long as the numbers are less than 1000, try this:
As #Mr1158pm said:
public class Chapter4Exercise2 {
public static void main(String[] args) {
int tableSize = 10;
int[][] table = new int[tableSize][tableSize];
for(int i=0; i < table.length; i++) {
for (int j=0; j < table[i].length; j++) {
table[i][j] = (i+1)*(j+1);
if(table[i][j] < 10) //Where i*j < 10
System.out.print(" "+(table[i][j])+" ");
else if(table[i][j] < 100) //Where i*j < 100
System.out.print(" "+(table[i][j])+" ");
else //Where i*j < 1000
System.out.print(" "+(table[i][j])+" ");
}
System.out.println("");
}
I don't think that you have to declare an array data structure to print out this table.
Just use two nested for loops and do calcs in the loops.
Here is a working method that you can work on. Just need to fix column alignment, add space here and there.
FYI row<10?" "+row:row is a form on inline if statement. If you haven't seen it before google it. It's quite useful.
public static void main(String[] args) {
for(int row=0; row<13; row++)
{
for(int col=0; col<13; col++)
{
if(row==0) //ffirst row
{
if(col==0)
System.out.print(" ");
else
System.out.print(col<10?" "+col:" "+col);
}
else
{
if(col==0)
System.out.print(row<10?" "+row:row);
else
System.out.print(row*col<10?" "+(row*col):(row*col<100? " "+(row*col):" "+(row*col)));
}
}
System.out.println();
}
}
import java.util.Scanner;
public class Back {
public static void main(String[] args) {
Scanner a1 =new Scanner(System.in);
int row,col;
String ch;
System.out.println("Enter width of screen:");
row = a1.nextInt();
System.out.println("Enter height of screen:");
col = a1.nextInt();
System.out.println("Enter background character:");
ch =a1.next();
String twoD[][] = new String[row][col];
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++){
twoD[i][j] = ch;
}
for(i=0;i<row;i++){
for(j=0;j<col;j++)
System.out.print(twoD[i][j]+" ");
System.out.println();
}
int width = 10;
int height = 10;
int[][] table = new int[width][height];
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
System.out.print(" " + table[i][j] + " ");
}
System.out.println("");
}