Changing elements in a two dimensional array - java

What I'm trying to do is generate a 15x15 square of "-" and accept a user input coordinate which will then replace the "-" with a "x" currently my program is just printing a vertical line of "-"
import java.util.*;
public class GameOfLife
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
}
else
System.out.printf("-", boardList[i][j]);
System.out.println();
}
}
}
}
}
}

here you have , this works ... u need to put System.out.println(); outside inner loop as well as put
if(xCoordinate == i){
if(yCoordinate == j){
to one condition ...
public static void main(String[] args) {
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = true;
do {
System.out
.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1) {
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (xCoordinate == i && yCoordinate == j) {
System.out.printf("x", boardList[i][j]);
} else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
}
} while (done);
}
//EDIT note that i changed done to true just to demonstrate that it works ...

try this
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i && yCoordinate==j)
System.out.printf("x", boardList[i][j]);
else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
You need to print the new line after you finish printing a whole row first

If I understand well, You want a two dimensional array initialized with '-', to do so you could do
int[][] boardList = new int[15][15];
for (int row = 0; row < 15; row ++)
for (int col = 0; col < 15; col++)
boardList[row][col] = '-';
And then, once you store the user data in xCoordinate and Ycoordinate, you simple do:
boardList[xCoordinate][Ycoordinate] = 'x';

You can try this code:
import java.util.Scanner;
public class StackOverflow
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
System.out.println();
}
}
}
}

Related

Java Homework trouble asterisks

I am having trouble coding. Im trying to make a program that will ask a user to input height and width for a shape. Considering I am taking a java class, I am a newbie. There needs to be two parallel shape of asterisks, can be a square or rectangle.
Thanks!
The code I have so far is kinda frankensteined in
import java.util.Scanner;
public class rectangle {
public static void main(String... args) {
int recHeight = 0;
int recWidth = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter height [-1 to quit] >> ");
recHeight = input.nextInt();
if (recHeight == -1) {
System.exit(0);
}
/* check if number is valid */
if (recHeight < 2 || recHeight > 24) {
System.err.println("--Error: please enter a valid number");
continue; // prompt again
System.out.print("Enter width [-1 to quit] >> ");
recWidth = input.nextInt();
if (recWidth == -1) {
System.exit(0);
}
/* check if number is valid */
if (recWidth < 2 || recWidth > 24) {
System.err.println("--Error: please enter a valid number");
continue; // prompt again
}
for (int col = 0; col < recHeight; col++) {
for (int row = 0; row < recWidth; row++) {
/* First or last row ? */
if (row == 0 || row == recWidth - 1) {
System.out.print("*");
if (row == recWidth - 1) {
System.out.println(); // border reached start a new line
}
} else { /* Last or first column ? */
if (col == recHeight - 1 || col == 0) {
System.out.print("*");
if (row == recWidth - 1) {
System.out.println();
}
} else {
System.out.print(" ");
if (row == recWidth - 1) {
System.out.println();
}
}
}
}
}
}
} while (true);
}
}
I have no idea what they are teaching you with the if and continue's. I think you created an endless loop with do while(true) because you never set it to false.
Here is how we were taught last week, or at least modified to what you need.
import java.io.*;
import java.util.Scanner;
public class SquareDisplay
{
public static void main(String[] args) throws IOException
{
// scanner creation
Scanner stdin = new Scanner(System.in);
// get width
System.out.print("Enter an integer in the range of 1-24: ");
int side = stdin.nextInt();
// check for < 1 or greather then 24
while( (side < 1) || (side > 24))
{
System.out.print("Enter an integer in the range of 1-24: ");
// reget the side
side = stdin.nextInt();
}
// get height
System.out.print("Enter an integer in the range of 1-24: ");
int height = stdin.nextInt();
// check for < 1 or greather then 24
while( (height < 1) || (height > 24))
{
System.out.print("Enter an integer in the range of 1-24: ");
// reget the height
height = stdin.nextInt();
}
// create rows
for( int rows = 0; rows < side; rows++)
{
// creat cols
for( int cols = 0; cols < height; cols++)
{
System.out.print("X");
}
System.out.println();
}
}
}
The following does what you want, and also covers the case they input an invalid number such as example
import java.util.InputMismatchException;
import java.util.Scanner;
public class SquareDisplay {
public static void main(final String... args) {
try (Scanner input = new Scanner(System.in)) {
final int columns = getInRange(input, 1, 24);
final int rows = getInRange(input, 1, 24);
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
System.out.print("X");
}
System.out.println();
}
}
}
private static int getInRange(final Scanner input, final int min, final int max) {
int returnValue = Integer.MIN_VALUE;
do {
System.out.printf("Please enter a value between %d and %d: ", min, max);
try {
returnValue = input.nextInt();
} catch (final InputMismatchException ignored) {
// Ignore, keep asking
}
input.nextLine();
} while (returnValue < min || returnValue > max);
return returnValue;
}
}
Optimisations
Using try-with-resources to handle resource management
Extracting reading the number to reduce duplication
Handling the InputMismatchException to stop it killing the program

Module and how to use it in the situation below

public class AirplaneLab
{
private int [][] first;
private int [][] economy;
private boolean [] seat;
private boolean okay;
private boolean okayokay;
public AirplaneLab()
{
}
public AirplaneLab(int [][] first1, int [][] economy1)
{
}
public boolean viewFirstClass(boolean set[], int [][] first, int [][] economy)
{
if (okay = true)
{
boolean seating1[] = new boolean[20];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if(seat[((j + 1) + (i * 4)) - 1])
{
System.out.print("x ");
seating1[i * j] = true;
}
else
{
System.out.print("o ");
seating1[i * j] = flase;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating1[];
}
else
{
return false;
}
}
public boolean viewEconomyClass(boolean set[], int [][] first, int [][] economy)
{
if (okayokay = true)
{
boolean seating2[] = new boolean[30];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
if(seat[((j + 1) + (i * 3)) - 1])
{
System.out.print("x ");
seating2[i * j] = true;
}
else
{
System.out.print("o ");
seating2[i * j] = false;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating2[];
}
else
{
return false;
}
}
public void decision()
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1 for “booking in first class”");
System.out.println("2 for “booing in economy class”");
System.out.println("3 to view seating chart for first class ");
System.out.println("4 to view seating chart for economy class");
System.out.println("0 to exit");
System.out.print("? ");
while(true)
{
int mOpt = input.nextInt();
if ((mOpt == 1) || (mOpt == 3))
{
if (mOpt == 1)
{
okay = true;
System.out.println("Based on the following setting arrangement, please pick a window middle or end seat");
viewFirstClass(boolean set[], int [][] first, int [][] economy);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (seating1[i * j] == true)
{
if ((i * j) ________________)
}
}
}
}
}
}
}
}
In the code above, where the blank is:
The last if statement before all of the closed brackets:
I was wondering how you would use module there.
Let's say I wanted to do (i * j) module of 4; how would I do that? Can you fill in the blank? Thank you for your help!
If you are looking for some thing (modulo) like
if ((i * j) mod 4 )
in java ,the syntax would be
if ((i * j) % 4 )

2D arrays that change with user input

I've been asked to make a program that prints a 5x5 grid that allows users to input an integer to determine where an "x" will be put. e.g if the user inputs 1 it would print out.
x 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Here's my code. I've built the array but I just can't seem to get it to print out the array where the inputted integer has an effect. Also would I just loop the same code again and again until someone wins or all spaces have been filled.
import java.util.Scanner;
public class Grade {
static Scanner input = new Scanner(System. in );
public static void main(String[] args) {
final int rows = 5;
final int columns = 5;
int one;
int two;
int[][] grid = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("");
}
System.out.println("player one choose your position");
one = input.nextInt();
while (one > 25 || one < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}
System.out.println("player two choose your position");
two = input.nextInt();
while (two > 25 || two < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("" + one);
}
}
}
The code you need to do what you are asking is posted below. Since x is an int in your code you needed an algorithm to make it so that you could set the location properly in the int[][].
import java.util.Scanner;
public class GradeSO
{
Scanner input = new Scanner(System. in);
int remainder;
int down;
int column;
int row;
int rows = 5;
int columns = 5;
int one;
int two;
int[][] grid;
public void makeLocation(int x, int r, int c)
{
remainder = x % c;
down = (int) x / r;
if(x % c!=0)
{
column = remainder-1;
}
else
{
column = remainder;
}
if(x % c==0)
{
row=down-1;
column = remainder+4;
}
else
{
row=down;
}
}
public void makeArray()
{
grid = new int[rows][columns];
System.out.println("Player 1: Please chose a number between 1 and 25");
one = input.nextInt();
while (one > 25 || one < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 1: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}
makeLocation(one,columns,rows);
grid[row][column]= 1;
System.out.println("Player 2: Please chose a number between 1 and 25");
two = input.nextInt();
while (two > 25 || two < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 2: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}
makeLocation(two,columns,rows);
grid[row][column]= 2;
}
public void displayArray()
{
for (int[] smallGrid: grid)
{
for (int elem: smallGrid)
{
System.out.print(elem);
}
System.out.println();
}
}
public static void main(String[] args)
{
GradeSO gSO = new GradeSO();
gSO.makeArray();
gSO.displayArray();
}
}

How to make a newline for every 15 spaces with numbers in java

I have the following code that finds the prime factors from 1 to the user input. The problem is that the output is in one very long line, I want every 15 numbers to output then go to the next line. How would I do that?
Here is my code:
public static void main (String args[])
{
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
input.nextLine();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
CompositeNumbers(PrimeFactor);
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" ");
}
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
You could do something like this:
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (i > 0 && i % 15 == 0) System.out.println();
System.out.print(PrimeFactor.get(i));
System.out.print(" ");
}
You could just have a counter and take a mod of this counter value for 15 and print it in the next line, like below. Like #soong described
int counter = 0;
for (int value : PrimeFactor)
{
if(counter % 15 == 0){
System.out.println();
}
System.out.print(value);
System.out.print(" ");
counter++;
}

Printing A Diamond Shape In Java, Based On User Input

I have a problem with a program I am trying to write. A user inputs a positive odd integer, otherwise the program prompts the user until they do. When they do, the program prints a diamond shape corresponding to the user input.
I have this piece so far that prints the left hand diagonal of such a figure, but cannot figure out how to print the rest of it. Here is the code:
import java.util.Scanner;
public class DrawingProgram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
userInput = keyboard.nextInt();
if (userInput%2 == 0){
System.out.println("That is not a Positive Odd Integer!");
}
else if (userInput < 0){
System.out.println("That is not a Positive Odd Integer");
}
else if (userInput%2 == 1){
for (int row = 1; row<= userInput; row++){
for (int col = 1; col<= userInput; col++ ){
if (row+col==userInput-1 )
System.out.print( "*");
else
System.out.print( " ");
}
System.out.print("\n");
}
}
}
}
A user inputs a positive odd integer, otherwise the program prompts
the user until they do
You need to scan in a loop
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
System.out.println("That is not an Odd Integer!");
if(userInput < 0)
System.out.println("That is not a Positive Odd Integer");
} while(userInput < 0 || userInput %2 == 0);
Now you can remove that validation else if (userInput%2 == 1){
Now the first thing I realize when checking at your loop is if (row+col==userInput-1 || ) which won't compile as you have a comparison operator with nothing following.
Note that you can replace System.out.print("\n"); with System.out.println("") but that's not really important...
Now replace your loop condition so that they start as 0
for (int row = 0; row <= userInput; row++){
for (int col = 0; col <= userInput; col++ ){
Now since you want a Diamond, you need to have 4 diagonal, so 2 loops (one for top and bottom)...
for (int i = 1; i < userInput; i += 2)//Draw the top of the diamond
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//Output correct number of spaces before
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)//Output correct number of asterix
{
System.out.print("*");
}
System.out.print("\n");//Skip to next line
}
for (int i = userInput; i > 0; i -= 2)//Draw the bottom of the diamond
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
So the final code would look like this
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
{
System.out.println("That is not an Odd Integer!");
}
if (userInput < 0)
{
System.out.println("That is not a Positive Odd Integer");
}
} while (userInput < 0 || userInput % 2 == 0);
for (int i = 1; i < userInput; i += 2) //This is the number of iterations needed to print the top of diamond (from 1 to userInput by step of two for example with 5 = {1, 3, 5} so 3 rows.
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//write correct number of spaces before, example with 5 = j < 5 - 1 -i / 2, so it would first print 4 spaces before, with 1 less untill it reach 0
{
System.out.print(" ");//write a space
}
for (int j = 0; j < i; j++)
{
System.out.print("*");//write an asterix
}
System.out.println("");
}
// Same logic apply here but backward as it is bottom of diamond
for (int i = userInput; i > 0; i -= 2)
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}

Categories