I am trying to create a program that lets you find how many times a curtain number occurs in a 2d array. One of the things that I am required to do is to create a method called countInstence which counts the amount of times a number occurs but also where they are located in the array. the problem i'm having is how do I output the location of the the number
public int[][] createArray(int rSize, int cSize) {
Random rnd = new Random();
int[][] array = new int[rSize][cSize];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = rnd.nextInt(26);
}
}
return array;
}
public void print2dArray(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println("\n");
}
}
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
count++;
}
}
return count;
}
public static void main(String[] args) {
Journal5b call = new Journal5b();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
}
Just insert a one line print statement inside of the if-statement and format to print the row and column of the current index, as below...
public int countInstance(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);
count++;
}
}
}
return count;
}
If you aren't familiar with the System.out.printf call or the %d symbols, you can read more about it here.
Just add this line to the for loop
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);// add this line
count++;
}
}
}
If you want to also use location at other place then just declare a List and add location to that list while searching for element.
public static List<String> location=new ArrayList<String>();
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
{
count++;
String loc=row+","+col;
location.add(loc);
}
}
}
return count;
}
public static void main(String[] args) {
Test call = new Test();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
System.out.println("locations :");
for(int i = 0; i < location.size(); i++) {
System.out.println(location.get(i));
}
}
I suggest using Points:
List<Point> locations=new ArrayList<Point>();
....
if (array[row][col] == search)
{
count++;
locations.add(new Point(row,col));
}
Related
int[][] numList = new int[10][10];
int column;
for (int row = 0; row < 10; row++) {
for (column = 0; column < 10; column++) {
numList[row][column] = (int) (Math.random() * 100);
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
public class Test1 {
public static void main(String[] args) {
int numList[][]=new int[10][10];
int max=0;
int min=999;
int minX=0;
int maxX=0;
int minY=0;
int maxY=0;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
int num=(int)(Math.random()*100);
numList[row][column] = num;
if(num>max){
max=num;
maxX=row;
maxY=column;
}
if(num<min){
min=num;
minX=row;
minY=column;
}
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
System.out.println("Max value=>"+max+"["+maxX+","+maxY+"]");
System.out.println("Min value=>"+min+"["+minX+","+minY+"]");
}
}
Your code is only inserting data into 2 dimensional array. To find min and max inside array and its corresponding index you need to write a function search as shown follow:
public class prog{
public void search( int[][] numList )
{
int max=0;
int maxX=0;
int maxY=0;
int min=0;
int minX=0;
int minY=0;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
if( min > numList[row][column])
{
min = numList[row][column];
minX=row;
minY= column;
}
if( max < numList[row][column])
{
max= numList[row][column];
maxX=row;
maxY=column;
}
}
}
System.out.print("MinX:"+ minX+ " MinY: "+ minY+ " MaxX:"+ maxX+ " MaxY:"+ maxY);
}
public static void main(String[] args){
int[][] numList = new int[10][10];
int column;
for (int row = 0; row < 10; row++) {
for (column = 0; column < 10; column++) {
numList[row][column] = (int) (Math.random() * 100);
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
prog obj = new prog();
obj.search( numList);
}
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.
I'm writing a program that reads a file and sees if the information make up a magic square, but I am getting this error: "java.lang.ArrayIndexOutOfBoundsException: 3" in my sumCol method. Specifically the line below: for (int row = 0; row < square[row].length; row++) {
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square[row].length; row++) {
sum += square[row][col];
}
return sum;
}
I'm not sure if it is necessary, but here is the rest of my class as well:
// ****************************************************************
// Square.java
//
// Define a Square class with methods to create and read in
// info for a square matrix and to compute the sum of a row,
// a col, either diagonal, and whether it is magic.
//
// ****************************************************************
import java.util.Scanner;
public class Square {
int[][] square;
//--------------------------------------
//create new square of given size
//--------------------------------------
public Square(int size) {
square = new int[size][size];
for (int row = 0; row < square.length; row++) {
for (int col = 0; col < square.length; col++) {
square[row][col] = row * 10 + col;
}
}
}
//--------------------------------------
//return the sum of the values in the given row
//--------------------------------------
public int sumRow(int row) {
int sum = 0;
for (int col = 0; col < square.length; col++) {
sum += square[row][col];
}
return sum;
}
//--------------------------------------
//return the sum of the values in the given column
//--------------------------------------
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square[row].length; row++) {
sum += square[row][col];
}
return sum;
}
//--------------------------------------
//return the sum of the values in the main diagonal
//--------------------------------------
public int sumMainDiag() {
int sum = 0;
for (int j = 0; j < square.length; j++) {
sum += square[j][j]; //you can do this because a square's diagonals have the same coordinate points
}
return sum;
}
//--------------------------------------
//return the sum of the values in the other ("reverse") diagonal
//--------------------------------------
public int sumOtherDiag() {
int sum = 0;
for (int j = 0; j < square.length; j++) {
sum += square[j][square.length - 1 - j];
}
return sum;
}
//--------------------------------------
//return true if the square is magic (all rows, cols, and diags have
//same sum), false otherwise
//--------------------------------------
public boolean magic() {
boolean answer = true;
int sum = sumMainDiag();
if (sumOtherDiag() != sum) {
answer = false;
} else {
for (int col = 0; col < square.length; col++) {
if (sum != sumCol(col)) {
answer = false;
}
}
for (int row = 0; row < square.length; row++) {
if (sum != sumRow(row)) {
answer = false;
}
}
}
return answer;
}
//--------------------------------------
//read info into the square from the input stream associated with the
//Scanner parameter
//--------------------------------------
public void readSquare(Scanner scan) {
for (int[] square1 : square) {
for (int col = 0; col < square.length; col++) {
square1[col] = scan.nextInt();
}
}
}
//--------------------------------------
//print the contents of the square, neatly formatted
//--------------------------------------
public void printSquare() {
for (int[] square1 : square) {
for (int col = 0; col < square1.length; col++) {
System.out.print(square1[col] + "\t");
}
System.out.println();
}
}
}
change
row < square[row].length
to:
row < square.length
Perhaps you meant this?
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square.length; row++) {
sum += square[row][col];
}
return sum;
}
Notice that the number of rows is given by square.length, whereas the number of columns in a given row is given by square[row].length.
You're doing the check wrong. Use:
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square.length; row++) {
sum += square[row][col];
}
return sum;
}
You're checking the length of the row, not of the overall array.
I think you want
// square.length not square[row].length
for (int row = 0; row < square.length; row++) {
// Here's where we might check square[row].length to be safe.
if (col < square[row].length) {
sum += square[row][col];
}
}
The following code is supposed to take a String array of one element ,splits it into
nine elements those nine elements should be store into another array of two dimensions .
each element of them should be store in a column alone.
But when I print the elements of the two dimensional array the last element only is printed
Why?
public class StringFragementation {
public static String[][] mymethod(String[] mystring) {
String[][] india = new String[1][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
do {
i = mystringno2[j].indexOf(x, i);
i1 = i + 1;
i1 = mystringno2[j].indexOf(x, i1);
if (i1 <= -1) {
break;
}
i++;
int row, col = 0;
for (row = 0; row < 1; row++) {
for (col = 0; col < 9; col++) {
india[row][col] = mystringno2[j].substring(i, i1);
}
}
}
while (j < mystringno2.length);
return india;
}
public static void main(String[] args) {
String[][] singapore = new String[1][9];
String[] s = {"_Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia_"};
singapore = mymethod(s);
for (int row = 0; row < 1; row++)
for (int col = 0; col < 9; col++) {
System.out.print(singapore[0][0] + "\t");
}
}
}
the problem is here :
for( row=0;row<1;row++){
for( col=0;col< 9;col++) {
india[row][col] = mystringno2[j].substring(i, i1);
}
}
you fill the 9 column by the same word because the i and i1 never change through this loop , then restart the array and fill with Netherlands then Iceland_Norway_Denmark until the last word
Bolivia , so your array fill with Bolivia in 9 columns
the correct way is :
int row = 0, col = 0;
String[][] india = new String[1][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
do {
i = mystringno2[j].indexOf(x, i);
i1 = i + 1;
i1 = mystringno2[j].indexOf(x, i1);
if (i1 <= -1) {
break;
}
i++;
india[0][col] = mystringno2[j].substring(i, i1);
System.out.println("dfref " + row + " " + col + " " + india[row][col]);
col++;
} while (j < mystringno2.length);
return india;
and in the main :
for (int row = 0; row < 1; row++) {
for (int col = 0; col < 9; col++) {
System.out.print(singapore[row][col] + "\t");
}
}
there are a smallest way to do this split , look at this code :
class StringFragementation {
public static String[] mymethod(String mystring) {
String[] split = mystring.split("_");
return split;
}
public static void main(String[] args) {
String[] singapore = new String[9];
String s = "Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia_";
singapore = mymethod(s);
for (int col = 0; col < 9; col++) {
System.out.println(singapore[col]);
}
}
}
I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}