JAVA Need help involving matrices and arrays - java

I'm working on a test prep program. Its not homework or for a grade, I just need help finishing and fixing it so I can study and better understand how it works. The directions are "Write a program named Matrix1.java that randonly fills in 0s and 1s into an n-by-n matrix, prints the matrix." I'm still pretty new to coding so any help would be greatly appreciated. This is the code I have so far:
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix=new Matrix1(5);
matrix.fill();
matrix.print();
}
public Matrix1(int n){
int[][] matrix = new int[n][n];
}
public void fill(int n){ // randomly fill in 0s and 1s
Random rand = new Random();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
Integer r = rand.nextInt;
matrix[i][j] = Math.abs(r);
}
}
}
public void print(int[][]matrix, int n){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.println(array[i][j]);
}
}
}
}
I ended up confusing myself and I'm not sure how to fix it or continue. I think I'm partially on the right track though.

Your code after fixes.
import java.util.Random;
public class Matrix1 {
private final int[][] matrix;
private final int n;
public Matrix1(int n) {
this.n = n;
this.matrix = new int[n][n];
}
/**
* randomly fill in 0s and 1s
*/
public void fill() {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rand.nextInt(2);
}
}
}
/**
* print the matrix, each row is printed in a separate line
*/
public void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
}
So changes I've made:
I've changed "matrix" and "n" variables into class fields, so you don't have to pass them through class methods
filling array - it should be just 0/1 not any integer so you can use rand.nextInt(2) with bounds - it gives values less then 2
printing array - you have to print row in one line, then change line

It looks like the right direction, check your main method to set the necessary parameters (size, array and size).
Also set the Random object to only be 0 or 1 (Check the Java class libraries for the answer) I believe you can set a parameter inside the Random.nextInt method.
Also if its required to print it like a double array, change up your printing logic since you are always writing to a new line

Well, I see a few problems, which if fixed might help get you on the right track.
First of all, for the random integer, you'll probably want to use the method from this answer:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);
I don't think you need to use Math.abs in this case, as long as you call ThreadLocalRandom.current().nextInt(0, 2).
Second, there are a couple of problems with your printing code. First of all, you should be using matrix[i][j] instead of array[i][j]. Second, you'll want to use System.out.print instead of System.out.println.
It should be something like this:
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}

public class Matrix1{
public static void main(String[] args){
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
private int[][] m; //it is easier use a global variable
public Matrix1(int n){
m = new int[n][n];
}
public void fill(){ // randomly fill in 0s and 1s
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++){
if (Math.random() > 0.5) {
m[i][j] = 1;
} else {
m[i][j] = 0;
}
}
}
}
public void print(){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< m.length; i++){
for(int j = 0; j<m.length; j++){
System.out.print(m[i][j]); //only use print() for the same row
}
System.out.println("");
}
}
}

Related

Why are my arrays returned blank from a method but the code works fine when running in the main-Method?

I'm having following problem with my program.
It's a "connect four" Java console application.
When starting my program, I reset 3 things.
A multi-dimensional char array
public final int rows = 8, columns = 8;
public char[][] board = new char[rows][columns];
I reset it with a for-loop, overwriting every array field with the character '.', which is my default board texture.
public char[][] resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
return board;
}
An integer-array
public int[] nums = new int[columns];
I reset it with a for-loop using the variable i, since I just need an array with the length of columns, which just counts up from 1. It is used so the user know which column he's choosing. Like in chess "A6" e.g., except without letters.
public int[] resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
return nums;
}
An integer
public int roundCounter = 0;
The integers keeps track of how many rounds there have been in the current game. I want it to be printed while playing.
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return roundCounter = 0;
}
I reset these looking like this:
gameMain main = new gameMain();
gameMode mode = new gameMode();
gameCheck check = new gameCheck();
main.board = main.resetBoard();
main.nums = main.resetNums();
check.roundCounter = check.resetRoundCounter();
My problem is when printing the game board, the nums-array and the round counter none seem to work.
The game board is just completely blank. The nums-array is only 0's and the round counter stays at 0.
When running the code in the main-method it worked better than running it through classes etc.
My print method:
public void printBoard() {
gameMain main = new gameMain();
gameCheck check = new gameCheck();
// Printing number array with space in between the elements
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
// Printing the round count next to the number array
System.out.println(" Round " + check.getRoundCounter());
for (int i = 0; i < main.rows; i++) {
for (int j = 0; j < main.columns; j++) {
System.out.print(main.board[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
System.out.println("\n");
}
I could really use some help, since I've been up all night. Originally due to how much fun I was having programming this, now it has become frustrating.
Thanks for reading and thanks in advance!
I think what is happening to you is related to the references of the objects you are using. You are mixing two different ways of working, I give you an example:
You can use the reference of 'roundCounter' and work on it:
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
or you can return it, like this:
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return 0;
}
In the first case, you will have to call the function like this:
resetRoundCounter(); //this function changes the value of your variable.
In the second case, you will have to call the function like this:
roundCounter = resetRoundCounter();
You can choose the way you like to work but I recomend you not working with global variables especially working with methods. I hope it helps you.
Do it as
public void resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
}
public void resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
}
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
Finally, call them as follows:
gameMain main = new gameMain();
gameCheck check = new gameCheck();
main.resetBoard();
main.resetNums();
check.resetRoundCounter();
I also recommend you follow Java Naming Convention e.g. gameMain should be GameMain and gameCheck should be GameCheck.

Get Array length from one class to another class

i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem.
Testmatrix.java
public class TestMatrix{
int rows;
int cols;
double data[][] = new double[4][4];
public TestMatrix() {
super();
rows=1; cols=1;
for(int i=0; i<=rows;i++)
{
for(int j=0; j<=cols;j++)
{
data[i][j] = 0.0;
}
}
}
public void print(){
for (int i = 0; i <data.length ; i++) {
for (int j = 0; j <data[0].length ; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
Here is the main class
Main.java
public class Main {
public static void main(String[] args){
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's)
Thanks in advance **
When you create an array, you set the size, for example new double[4][4] then that's already the size of this array, even tho you didn't insert anything in there. My point is that no matter if you insert 1 element, 2 elements, or 8 elements, that doesn't matter, inserting to array doesn't change it's size (property returned by length). Imagine a bag, you have a bag with a certain size, doesn't matter if you put items in there, size of a bag is gonna stay the same.
You declared your array as a 4x4 matrix. Line 4 should be double data[][] = new double[2][2]; in order to achieve what you seem to want.
Initializing array doesn't change the size of an array. If you want to print acording to new row and column size, change your print() method to:
public void print() {
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
Again, constructor name should be same as class name. But the constructor of TestMatrix is Matrix.
Note: Another important thing, you don't need to initialize the double array to 0.0. This array is by default initialized to 0.0 as this is an instance field of the class. According to Oracle:
Each class variable, instance variable, or array component is
initialized with a default value when it is created.
For type double, the default value is positive zero, that is, 0.0d.
Also, change your TestMatrix(int rows, int cols, double[] data) constructor to:
// declare with a large size
double data[][] = new double[80][80];
public TestMatrix(int rows, int cols, double[] data) {
super();
this.rows = rows;
this.cols = cols;
for (int i = 0, k = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[k++];
}
}
}
Better practice would be making the fields private and write getter and setter methods for those fields.
Either declare matrix to 2*2 as said by Chris
or change
for (int i = 0; i < data.length ; i++) {
for (int j = 0; j < data.length ; j++) {
to
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
If you want any size of matrix upto 4*4 use second solution.
You probably want something like this;
public class Matrix {
public final double[][] values;
public final int rows;
public final int cols;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols]; // Automatically 0.0.
}
public void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.printf(" %6f", values[i][j]);
}
System.out.println();
}
}
}
Matrix m = new Matrix(2, 2);
...
rows and cols are redundant, as you already used values.length, and values[0].length.
A few notes:
Use an IDE, your code did not even compile, this is the minimum
effort you should put into any problem.
Declaring the array as double data[][] = new double[4][4]; makes an array that is 4 "boxes" wide and 4 "boxes" tall. each box will hold a data of the type specified, in your case a double which you are setting to 0.0
public class TestMatrix
{
int rows;
int cols;
double data[][] = new double[2][2];
public TestMatrix()
{
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j <= cols; j++)
{
data[i][j] = 0.0;
}
}
}
public void print()
{
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[0].length; j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
In Addition to above answers
i'm getting 4x4 matrix( with all 0's)
If you wanna find difference replace the existing lines with below code
data[i][j] = 1.0;
System.out.print(data[i][j]+" ");
Hope you understand the reason for getting all the 0's
Your class should be like this:
public class Test {
int rows;
int cols;
double data[][] = new double[2][2];
public void print() {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
System.out.print(" "+data[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test m1 = new Test();
m1.print();
}
}
and this part you can delete. You do not need it. This is not an initialization.
public void matrix() {
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++) {
for (int j = 0; j <= cols; j++) {
data[i][j] = 0.0;
}
}
}

Sudoku debugging issue

I'm working on a program that is supposed to take as input a solved Sudoku Puzzle and return if it is a valid solution or not (true or false).
My code is written and running with a few helper methods.
The isSolution method runs through 4 different things to check if the solution is valid or not.
I've written a valid solution as input that should return true.
When I check each of these 4 elements separately, they return true, when I check them together, they return false (which is wrong)
I've spent hours testing them separately, together and in different combinations.
I've tried with different inputs.
I can't figure out why it's returning false when it should be returning true.
Any help would be amazingly appreciated! Thanks
public static void main(String[] args){
int [][] solvedPuzzle = {
{8,3,5,4,1,6,9,2,7},
{2,9,6,8,5,7,4,3,1},
{4,1,7,2,9,3,6,5,8},
{5,6,9,1,3,4,7,8,2},
{1,2,3,6,7,8,5,4,9},
{7,4,8,5,2,9,1,6,3},
{6,5,2,7,8,1,3,9,4},
{9,8,1,3,4,5,2,7,6},
{3,7,4,9,6,2,8,1,5}
};
System.out.println(isSolution(solvedPuzzle));
}
////// Checks if the input is a valid sudoku solution
/* The solvedPuzzle input is a valid solution, so this method should return true.
* Each of the elements in this method return true when tested individually, but for some reason,
* when I run them all together, the method returns false
*/
public static boolean isSolution(int [][] solvedPuzzle){
//Checks if the rows and columns have 9 ints
if (solvedPuzzle.length != 9 || solvedPuzzle[0].length !=9){
return false;
}
//Checks if every column is made up of unique entries
for (int j = 0; j < 9; j++){
if (uniqueEntries(getColumn(solvedPuzzle, j)) !=true){
System.out.println("HERE!"); //these are just here to try to figure out WHERE I've gone wrong
return false;
}
}
//Checks if every row is made up of unique entries
for (int i = 0; i < 9; i++){
if (uniqueEntries(solvedPuzzle[i]) !=true){
System.out.println("HERE!!!");
return false;
}
}
//Checks if every sub 3x3 grid is made up of unique entries
for (int x = 0; x < 9; x = x+3){
for (int y = 0; y < 9; y = y+3){
if (uniqueEntries(flatten(subGrid(solvedPuzzle, x,y,3))) != true){
System.out.println("HERE22");
return false;
}
}
}
return true;
}
///Below are the helper methods
////// Creates a smaller grid of size m starting at indexI,indexJ (x,y).
public static int [][] subGrid(int [][] original, int indexI, int indexJ, int m){
int [][] subGrid = new int [m][m];
for (int i = indexI; i < indexI+m ; i++){
for (int j = indexJ; j < indexJ+m ; j++){
subGrid [i - indexI][j - indexJ] = original[i][j];
}
}
return subGrid;
}
////// Sorts the intergers in a 1D array in asceding order
public static int [] sort(int [] originalArray){
int temp;
for(int i = 0; i < originalArray.length - 1; i++){
for(int j = 0; j < originalArray.length - 1; j++){
if(originalArray[j] > originalArray[j+1]){
temp = originalArray[j];
originalArray[j] = originalArray[j+1];
originalArray[j+1] = temp;
}
}
}
return(originalArray);
}
////// Checks if the intergers in a 1D array are all unique by first using the sort method
public static boolean uniqueEntries(int [] original){
int [] sorted = sort(original);
for (int i = 0; i < original.length-1; i++){
if (sorted[i+1] == sorted[i]) {
return false;
}
}
return true;
}
////// Takes a 2D array where each subarray is of the same size and creates a 1D array made up of the i-th element of each sub array
public static int [] getColumn(int [][] original, int indexJ){
int [] column = new int[original[0].length];
for (int i = 0; i < original[0].length; i++){
column[i] = original[i][indexJ];
}
return column;
}
////// takes a 2D array and flattens it into a 1D array
public static int [] flatten(int [][] original){
int [] flattenedArray = new int[original.length*original[0].length];
int counter = 0;
for (int i = 0; i < original.length; i++){
for(int j = 0; j < original.length; j++) {
flattenedArray[counter] = original[i][j];
counter++;
}
}
return flattenedArray;
}
if you check your puzzle before and after running //Checks if every row is made up of unique entries you will see that you are actually changing the original format of your puzzle. So the next test is not going to run over the original puzzle but a sorted one! If you add a simple loop before and after the second test you will understand what I am talking about
for (int i = 0; i < 9; i++){ //ADD THAT LOOP BEFORE AND AFTER THE TEST
for (int j = 0; j<9; j++) {
System.out.print(solvedPuzzle[i][j]);
}
System.out.println();
}
System.out.println('\n');
//Checks if every row is made up of unique entries
for (int i = 0; i < 9; i++){
if (uniqueEntries(solvedPuzzle[i]) !=true){
System.out.println("HERE!!!");
return false;
}
}
for (int i = 0; i < 9; i++){
for (int j = 0; j<9; j++) {
System.out.print(solvedPuzzle[i][j]);
}
System.out.println();
}
the code above will help you visualise what the puzzle looks before and after the test. A test should never change the format/contents/attributes of anything tested. The results of the above will be:
835416927
296857431
417293658
569134782
123678549
748529163
652781394
981345276
374962815
123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
As you can see the original puzzle is not "original" anymore.
So as I told you on my comment, flipping the tests around will NOT actually fix the problem. Instead the bug will still be produced; but without any tests to run after it is not going to affect the CURRENT code.
Hope that helps
EDIT: I don't know if I will be online later on; so in the case that even that hint didn't help you find the bug so I am also going to give you the solution :p
The issue is that you are using the sort() method that doesn't ONLY return the array sorted BUT ALSO actually sorts the input array! SO in order to avoid that you simply need to pass in a copy of the array instead of the array itself whenever you are calling the sort method:
////// Checks if the intergers in a 1D array are all unique by first using the sort method
public static boolean uniqueEntries(int [] original){
int [] sorted = sort(original.clone()); //pass in a copy of the array
for (int i = 0; i < original.length-1; i++){
if (sorted[i+1] == sorted[i]) {
return false;
}
}
return true;
}

Printing pyramid in Java on the console

How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}

ArrayList rangecheck error

I'm trying to refer to an arraylist I've initiated in a method, but when I try to remove something from that ArrayList, I get an error saying that the size of my ArrayList is 0. However, after I set the values of the ArrayList, it prints out the size of the ArrayList, which I have called 'school'. Here is my code.
import java.util.*;
public class SchoolSolver{
public static ArrayList<Girl> school = new ArrayList<Girl>();
public static ArrayList<Girl> used = new ArrayList<Girl>();
public static void main(String[] args){
resetSchool();
//System.out.println(school.size());
boolean notPossible = false;
for(int i = 0; i < 7; i++){
if(notPossible){
resetSchool();
} else {
newDay();
}
for(int j = 0; j < 5; i++){
//randomGirl() is where my error happens
Girl leader = randomGirl();
used.add(leader);
}
}
}
/*Below are the two methods where I suspect the error may originate from */
public static void resetSchool(){
school.clear();
for(int i = 0; i < 15; i++){
//System.out.println("ran");
school.add(new Girl(i));
}
for(Girl g : school){
ArrayList<Girl> classmates = new ArrayList<Girl>();
for(int i = 0; i < 15; i++){
if(i!= g.getID()){
classmates.add(new Girl(i));
}
}
g.setClassmates(classmates);
}
}
public static Girl randomGirl(){
return school.remove(0);
}
Thanks and I appreciate the help!
You have a never ending loop
for(int j = 0; j < 5; i++)
See how you increment i instead of j. This means you keep on calling randomGirl, which removes a Girl from the list each time it is called. So after a while (15 times) your list becomes empty, and you still call randomGirl, which results in the exception

Categories

Resources