Bidimentional Array - java

Hi all my program consist of an 2 Dimension array,im reading 2 cordinates in a loop and triying to check if those cordinates in the array are alredy been filled with a asterisc,if this is true y want to re-enicialize my array with the default value "-", and if there is not an asterisc in that specified position y want to fill it in with a asterisc,im not sure if im going for the correct aproach.
this is part of my code.
thanks all.
String[][] matrix = new String[5][5];
String asterisc = "*";
String defaultValue = "_";
Scanner sc = new Scanner(System.in);
int a, b;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = defaultValue;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + "|");
}
System.out.println();
}
a = 0;
b = 0;
while (a >= 0 && b >= 0 && a < matrix.length && b < matrix.length) {
a = sc.nextInt();
b = sc.nextInt();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[a][b].equals(asterisc)) {
matrix[i][j] = defaultValue;
} else {
matrix[a][b] = asterisc;
}
}
}
}

There are unfortunately many things wrong with your code.
Also you have not explained what your algorithm is trying to do.
In brief, to set all asterisks to defaults, you can do
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if matrix[i][j].equals(asterisc){
matrix[i][j]=defaultValue;
}
}
System.out.println();
}
But
why are you using a while loop?
Why are you using a scanner?
Why are a and b initialised at zero, yet need to be greater than zero for the loop?
Are you really trying to re-initialise your whole array, every time the (a,b) item is asterisc?

I think it is not true.Suppose you have typed "6 6" in the terminal,then the variable a=6,and b=6,which is greater than the array length,and the program will throw a exception.I think the thing you may want to do can follow this codeļ¼š
while(true){
a = sc.nextInt();
b = sc.nextInt();
if(a<0||a>matrix.length||b<0||b>matrix.lenght)
break;
}

Related

How to print all pairs of an ArrayList with no duplicates

Just a simple question. I know to print all possible pairs, you do a nested for loop with a few more adjustments to be fancier. In my case, I want to take it a step up where pairs are not allowed to repeat or have 2 of the same integer in a pair.
For example: (0,0) is not allowed, but (0,1) is allowed. If (0,1) is a pair, then (1,0) is not allowed.
If I had integers "0,1,2,3", then my output would be
(0,0)(0,1)(0,2)(0,3)(1,2)(1,3)(2,3)
This is my current code that won't print pairs with 2 same integers, but repeated pairs still print.
for(int a = 0; a < 4;a++) {
numbers.add(a);
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
Thanks
for(int i = 0; i < 4; i++) {
for(int j = i; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
or
for(int i = 0; i < 4; i++) {
for(int j = i + 1; j < 4; j++) {
System.out.println("("+i+" , "+j+")");
}
}

Printing two dimensional array in Java

I'm trying to figure out what's wrong with my code for printing the two dimensional array
int[][] container = new int [3][6];
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <== 6; j++) {
System.out.print(contianer[i][j] + " ");
}
}
System.out.println();
<==is not an operator.
Array start from 0 to length - 1
you have a typo in your variable inside the for
System.out.println();must be executed inside the first for not outside.
int[][] container = new int [3][6];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(container[i][j] + " ");
}
System.out.println();
}

Sorting Two-Dimensional Array by Row

The requirement is to sort the rows of a two-dimensional array. I feel like my code is very close to being done, but I can't figure out why it isn't displaying the sorted array. I forgot to mention that we are not allowed to use the premade sorting methods. The problem is most likely in the sortRows method. Anyways, here's my code:
public class RowSorting
{
public static void main(String[] args)
{
double[][] numbers = new double[3][3];
double[][] number = new double[3][3];
int run = 0;
String answer = "";
while (run == 0)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-by-3 matrix row by row: ");
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
numbers[row][column] = input.nextDouble();
}
}
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
System.out.print(numbers[row][column] + " ");
}
System.out.print("\n");
}
System.out.println("The sorted array is: \n");
number = sortRows(numbers);
for(int row = 0; row < number.length; row++)
{
for(int column = 0; column < number[row].length; column++)
{
System.out.print(number[row][column] + " ");
}
System.out.print("\n");
}
System.out.print("\nWould you like to continue the program (y for yes or anything else exits): ");
answer = input.next();
if(answer.equals("y"))
{
continue;
}
else
break;
}
}
public static double[][] sortRows(double[][] m)
{
for(int j = 0; j < m[j].length - 1; j++)
{
for(int i = 0; i < m.length; i++)
{
double currentMin = m[j][i];
int currentMinIndex = i;
for(int k = i + 1; k < m[j].length; k++)
{
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
}
if(currentMinIndex != i)
{
m[currentMinIndex][j] = m[j][i];
m[j][i] = currentMin;
}
}
}
return m;
}
}
It looks like this block:
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
Will never happen. Because you just assigned currentMin to m[j][i] two lines before it. I believe you want to use k in that if check. Something like
if (currentMin > m[j][k]){
currentMin = m[j][k];
currentMinIndex = k;
}
As cited per ergonaut, you have a problem with the codeblock
if(currentMin > m[j][i]) ...
and also
m[currentMinIndex][j] = m[j][i];
However, you also have a problem with your for-loops.
for(int j = 0; j < m[j].length - 1; j++) ...
for(int i = 0; i < m.length; i++) ...
Both of these are oddly structured. You probably want to swap these for-loops so that you don't throw index exceptions. This will also cause you address the indices in your code. And modify your j-index for-loop to include the entire range.

Randomly populating a 2d array

I am using Java and working on 5X5 board game(represented as String[][]) and I looking for an efficient way to randomly place 3 "A"'s, 3 "B",s 3 "C"'s, 3 "D"'s on the board.
I thought about using a nested for loop inside of a while loop to go over each slot, and randomly assign letters to 'slots' on the board, but I want to possibly do it in one pass of the board, if there is a good way to randomly place all 15 letters on the board in one pass.
Any suggestions?
You can use an ArrayList to store the letters (and the empty cells, I'm using a dot . so you can recognize it in the output), then use Collections.shuffle() to put elements of the ArrayList in "random" places. Finally assign each letter to the String[][] array:
public static void main(String[] args)
{
String[][] board = new String[5][5];
List<String> letters = new ArrayList<>();
// fill with letters
for (int i = 0; i < 3; i++) {
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
}
// fill with "empty"
for (int i = 0; i < 10; i++) {
letters.add(".");
}
Collections.shuffle(letters);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = letters.get(i*board.length + j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
Output Sample:
C B . . .
A E . E A
. A . D D
C . . . D
B C E . B
Note:
The operation i*board.length + j will generate consequent numbers 0, 1, 2, 3, ... 24 en the nested loop.
One way: create an ArrayList<Character> or of String, feed it the 15 letters, call java.util.Collections.shuffle(...) on the ArrayList, and then iterate over this List, placing its randomized items into your array.
e.g.,
List<String> stringList = new ArrayList<String>();
for (char c = 'A'; c <= 'E'; c++) {
for (int i = 0; i < 3; i++) {
stringList.add(String.valueOf(c));
}
}
for (int i = 15; i < 25; i++) {
stringList.add(null);
}
Collections.shuffle(stringList);
String[][] gameBoard = new String[5][5];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = stringList.get(i * gameBoard.length + j);
}
}
// now test it
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
System.out.printf("%-6s ", gameBoard[i][j]);
}
System.out.println();
}

2-dimensional array in Java

Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?
The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){
You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}
I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}
I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}

Categories

Resources