2D arrays that change with user input - java

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();
}
}

Related

Java Single Dimensional Arrays

Enter the integers between 1 and 50: 1 2 1 0
1 occurs 2 times
2 occurs 1 times
1 occurs 2 times
How can I do to get 1 occurs only 1 times ?
The problems is to it's print many times.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
Edit this Code
Try this (Refer to code comments for explanations):
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
while (i < 100) { // Check if the array is already full
System.out.print("Enter 0 to Exit or enter the integers between 1 and 50 (Input #" + (i + 1) + ") : ");
int value = input.nextInt();
if (value == 0) {
break;
}
if (value < 1 || value > 50) { // check if input is between 1 and 50
System.out.println("Input is not between 1 and 50");
} else {
num[i] = value;
System.out.println();
}
i++;
}
System.out.println();
System.out.println("Result: ");
for (int j = 0; j < i; j++) {
int n = 0;
boolean isAlreadyPrinted = false; // flag to check if will be printed or not
for (int k = 0; k < i; k++) {
if (num[j] == num[k]) {
if (j > k) { // this means that the same value is already found and printed
isAlreadyPrinted = true;
}
n++;
}
}
if (!isAlreadyPrinted) {
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
}
The problem is with your for loop.
You should not run the j's value up to i. That's why "1 occurs 2 times" is printing twice. What you have to do is checking the value of the array's certain index has been occurred multiple times before print part executed.
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean hasDuplicateValues (int[] array, int value )
{
boolean result = false ;
int count = 0 ;
for (int i=0 ; i< array.length; i++)
{
if(array[i] == value)
{
count = count+1 ;
}
}
if(count > 1)
{
result = true;
}
return result;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
int[] subarray = subArray(num, 0, i);
boolean isDuplicate = hasDuplicateValues (subarray , num[i] )
if(isDuplicate == false )
{
System.out.println(num[j] + " occurs " + n + " times");
}
}
}

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

How do I calculate the Average marks?

I'm making a histogram which collects the results of student marks and displays which marks are in a certain range e.g 0-29 or 70-100.
I'm trying to figure out how I can edit my code so that I can calculate the average mark. I know the average mark is calculated by adding all numbers and dividing by the amount of numbers but I'm having trouble implementing that into my program.
Here's my code:
public static void main(String[] args) {
int studentMark = 0;
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
int firstRange = 0; // (1)
int secondRange = 0; // (2)
int thirdRange = 0; // (3)
int fourthRange = 0; // (4)
// counts all 'mark' attempts (except anything > 100)
int numberOfStudents = 0;
Scanner input = new Scanner(System.in);
do{
System.out.println("Enter a mark from 1-100: ");
studentMark = input.nextInt();
if (studentMark < 29)
{
firstRange++;
numberOfStudents++;
}
if ((studentMark > 29) && (studentMark <= 39))
{
secondRange++;
numberOfStudents++;
}
if ((studentMark <= 69) && (studentMark > 39))
{
thirdRange++;
numberOfStudents++;
}
if ((studentMark <= 100) && (studentMark > 69))
{
fourthRange++;
numberOfStudents++;
}
}while ((studentMark <= 100))
System.out.println("\nResults: \n");
System.out.println("Number of students in total: " + numberOfStudents);
System.out.println("\nStudents who ranged from 0-29: " + firstRange );
System.out.println("Students who ranged from 30-39: " + secondRange);
System.out.println("Students who ranged from 40-69: " + thirdRange);
System.out.println("Students who ranged from 70-100: " + fourthRange);
}
In addition to counts for each range, you need to keep total of all grades and total count (or just add individual range totals)
The border tests are redondant and at least two cases aren't treated:
- rank = 29
- rank < 0
Below a simplified code:
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
final int[] roofs = new int[] {30, 40, 70, 101};
final int[] compters = new int[roofs.length];
final double[] sums = new double[roofs.length];
final double[] means = new double[roofs.length];
final Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a mark from 0-100: ");
final int studentMark = input.nextInt();
int index = -1;
if (studentMark < 0) {
continue; // here to be ignored
} else if (studentMark < roofs[0]) {
index = 0;
} else if (studentMark < roofs[1]) {
index = 1;
} else if (studentMark < roofs[2]) {
index = 2;
} else if (studentMark < roofs[3]) {
index = 3;
} else {
break;
}
compters[index]++;
sums[index] += studentMark;
} while (true);
input.close();
final int numberOfStudents = Arrays.stream(compters).sum();
IntStream.range(0, roofs.length).forEach(i -> means[i] = sums[i] / compters[i]);

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

Changing elements in a two dimensional array

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();
}
}
}
}

Categories