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]);
}
}
}
Related
This is for a school project. I need to read numbers from a .txt file and put them into an array. After they're in an array, I need to pass it into a different class to do the math and compare the numbers. The only problem is, I can't get the code to read the .txt file or make it into an array.
I need to use
if (sq.isMagicSquare())
to pass the array to class Square, but it gives the error:
required: int[][]
found: no arguments
reason: actual and formal lists differ in length
public class MagicSquareTester
{
public static void main() throws IOException
{
Square sq = null;
System.out.println("Enter the name of your data file (magicData.txt):");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine(); // input data file name from keyboard
Scanner inFile = new Scanner(new File (fileName));
int sqSize = inFile.nextInt(); // read the size
while (sqSize != -1)
{
sq = new Square(sqSize, inFile);
if (sq.isMagicSquare()) //will return true or false
System.out.println("\tWe have a Magic Square!");
else
System.out.println("\tThis is NOT a Magic Square.");
System.out.println(sq);
System.out.println();
sqSize = inFile.nextInt();
}
System.out.println("Of the " + sq.getTotalTested() + " squares tested " + sq.getMagicCount() + " were magic square(s)" );
}
}
public class Square
{
Scanner scan = new Scanner(System.in); //has been imported correctly, btw
int tested = 0, areMagic = 0, sqSize;
boolean magic;
int[][] Square;
public Square(int sqSize, Scanner inFile)
{
Square = new int [sqSize] [sqSize];
}
public void readSquare(Scanner inFile)
{
for(int row = 0; row < sqSize; row++)
for(int col = 0; col < sqSize; col++)
{
Square[row][col] = inFile.nextInt();
tested++;
}
}
public boolean isMagicSquare(int[][] array)
{
Sums testMagic = new Sums();
int rows = testMagic.sumRows(array);
int cols = testMagic.sumCol(array);
int diagonals = testMagic.sumDiagonal(array);
if((rows == cols) && (cols == diagonals) && (diagonals == rows))
{
magic = true;
areMagic++;
}
else
magic = false;
return magic;
}
public int getMagicCount()
{
return areMagic;
}
public int getTotalTested()
{
return tested;
}
}
public class Sums
{
int sum = 0, lastSum = 0, counter1, counter2, counter3;
boolean magic = true;
public int sumRows(int [][] array)
{
for (int row = 0; row < array.length; row++)
{
sum = 0;
for (int col = 0; col < array.length; col++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter1++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter1;
}
public int sumCol(int [][] array)
{
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter2++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter2;
}
public int sumDiagonal(int [][] array)
{
int diagonal1 = 0, diagonal2 = 0;
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if(row == col)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal1 = sum;
}
}
}
for (int col = 0; col < array.length; col--)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if((row + col) == array.length - 1)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal2 = sum;
}
}
}
if(diagonal1 == diagonal2)
{
magic = true;
counter2 = counter3;
}
else
counter3 = 0;
return counter3;
}
}
Also, apologies if my code looks weirdly formatted. I've never posted here before and I'm doing my best.
I suggest you use java.io.file and separate the squaring and parsing operations from the file reading operations.
Possibly like follows:
public class MathSquareTester {
public static void main (String[] args) throws IOException {
List<Integer> squaredNums = new ArrayList<Integer>();
FileInputStream in = new FileInputStream(file_name);
BufferedReader reader = new BufferedReader(new FileReader(in));
String line = reader.readLine();
while (line != null) {
//Assuming each line represents a separate integer
squaredNums.add((int)Math.pow(Integer.parseInt(line)), 2);
line = reader.readLine();
}
int[] numsArray = new int[squaredNums.size];
squaredNums.toArray(numsArray);
//All of your numbers are now stored in numsArray
}
}
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));
}
I've created a 2 dimensional array with the same length and it is randomly filled with 1 and 0 for example.
0100
0010
1110
1111
How do I code the program to find the rows,columns and diagonals with all 1s and 0s
This is my code so far:
public class Test2dArray {
public static void main(String[] args) {
int row,column;
System.out.print("Enter the lenghth of matrix:");
Scanner input = new Scanner(System.in);
Random rand = new Random ();
int mSize = input.nextInt();
int [][] mArray = new int [mSize][mSize];
for (row=0; row < mSize; row++){
for(column=0; column < mSize; column++){
mArray[row][column]=rand.nextInt(2);
System.out.print(mArray[row][column]+ " ");
}
System.out.println();
}
}
}
Code isn't perfect (I'm sure it can be optimized) but it works
public static void main (String[] args) throws java.lang.Exception {
int row = 5;
int column = 5;
int [][] mArray = fillArray(row, column);
System.out.println("Rows: " + findRows(mArray));
System.out.println("Columns: " + findColumns(mArray));
System.out.println("Diags: " + findDiags(mArray));
}
private static ArrayList<Integer> findRows(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < mArray.length; i++){
boolean isRow = true;
for(int j = 0; j < mArray[0].length; j++){
if (j > 0 && mArray[i][j] != mArray[i][j - 1]) {
isRow = false;
break;
}
}
if (isRow) result.add(i);
}
return result;
}
private static ArrayList<Integer> findColumns(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j < mArray[0].length; j++){
boolean isColumn = true;
for(int i = 0; i < mArray.length; i++){
if (i > 0 && mArray[i][j] != mArray[i - 1][j]) {
isColumn = false;
break;
}
}
if (isColumn) result.add(j);
}
return result;
}
private static ArrayList<Integer> findDiags(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 1; i < mArray.length; i++) {
boolean isDiag = true;
for (int j = 0; j < i; j++) {
if (mArray[i - j][j] != mArray[i - j - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(i);
}
for (int i = 0; i < mArray.length - 2; i++) {
boolean isDiag = true;
for (int j = i + 1; j < mArray.length - 1; j++) {
if (mArray[mArray.length - j + i][j] != mArray[mArray.length - j + i - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(mArray.length + i);
}
return result;
}
private static int[][] fillArray(int row, int column) {
int [][] mArray = new int [row][column];
Random rand = new Random();
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
mArray[i][j] = rand.nextInt(2);
System.out.print(mArray[i][j] + " ");
}
System.out.println();
}
return mArray;
}
Iterate and for each row and columns and sum the values into rowSum and columSum.
So:
if (rowSum == mSize)
System.out.print("The row "+i+"is full of ones");
if (rowSum == 0)
System.out.print("The row "+i+"is full of zeros");
And the same, obviously, for the columns and diagonals.
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);
}
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("");}
}