Ok, so i want to create an integer matrix, say with 9 integers some positive and some negative like
int[][] myMatrix = {{1,5,-2},{7,9,3},{-4,-7,6}}
but i want to declare a String matrix of size 3 x 3. then Iterate through the integer matrix and if the current element has a positive integer put the word POSITIVE in the corresponding element in the String matrix, otherwise put NEGATIVE. my code prints fine when i run the matrix for integers but i'm confused how to write the condition for matrix. I already tried googling but nothing. here's my code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class 2D_Matrix {
public static void main(String[] args) throws IOException {
int [][] firstMatrix = {{1, 5, -2},{7, 9, 3},{-4 , -7, 6}};
String[][] secondMatrix = new String[3][3];
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
System.out.print(myMatrix[x][y] + "\t");
}
System.out.println();
}
}
}
i tried many different combinations but nothing works or throws errors. for example:
if(x < 0){
System.out.print("Negative");
}
else if(y < 0){
System.out.print("Negative");
}
else
{System.out.print("positive");
}
but it throws error stating y cannot resolve to a variable. Any help would be much appreciated.
I think what you want is
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
if(firstMatrix[x][y] < 0)
secondMatrix[x][y] = "NEGATIVE";
else
secondMatrix[x][y] = "POSITIVE";
}
}
About your validations
if(x < 0){
}
else if(y < 0){
}
else
{
}
You were validating the index, but index of an array can't be negative. According to your request, you want to validate if the value is negative or positive. Refer to my snippet for how to retrieve value and validate them.
Related
I have looked at other questions about out of bounds error and understood them, couldn't understand the fault in this code.
Question: A JAVA program that will read a boolean matrix corresponding to a relation R and output whether R is Reflexive, Symmetric, Anti-Symmetric and/or Transitive. Input to the program will be the size n of an n x n boolean matrix followed by the matrix elements.
The program must output a reason in the case that an input relation fails to have a certain property.
Solution: I have provided the code, it throws the "java.lang.ArrayIndexOutOfBoundsException" error at main and line 65. I can't see how my arrays are out of bounds
ERROR: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at XYZ.BooleanMatrix.main(BooleanMatrix.java:65)
Code:
package XYZ;
import edu.princeton.cs.algs4.*;
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
int n = StdIn.readInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (StdIn.readInt() != 0)
a[i][j] = true;
}
}
return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
int n = a.length;
StdOut.println(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j])
StdOut.print("1 ");
else
StdOut.print("0 ");
}
StdOut.println();
}
}
// random n-by-n matrix, where each entry is true with probability p
public static boolean[][] random(int n, double p) {
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = StdRandom.bernoulli(p);
}
}
return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in foreground
// color
public static void show(boolean[][] a, boolean which) {
int n = a.length;
StdDraw.setXscale(0, n - 1);
StdDraw.setYscale(0, n - 1);
double r = 0.5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, n - i - 1, r);
}
}
}
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //LINE 65
double p = Double.parseDouble(args[1]);
boolean[][] a = random(n, p);
print(a);
show(a, true);
}}
I don´t know the exact working of StdDraw.setXscale(0, n - 1); but i think it creates a table with n-1 rows. so if you try to fill it with n rows there will be an out of bounds error. try using this in line 47:
StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);
As stated in the comments below your post: if you don´t enter any arguments when calling the program you´ll get an out of bounds exception because the program expects arguments in the aray and there aren´t any.
To provide arguments open command line and call /java yourcompiledjavafile arg[0] arg[1]
I am currently writing a game engine for a game I'm making.
I'm writing a Map Object which uses Cell objects. A Cell is supposed to be a 128x128 area, which is represented by an array. Each int represents a object. However, when I run the following code for Cell generation:
private int[][] cellGen() {
int[][] tempMap = new int[128][128];
for (int x = 0; x < 128; x++) {
int y = 0;
for (y = 0; y < 128; y++) {
tempMap[y][x] = itemGen();
}
}
return tempMap;
}
However, it only generates one line of 128 ints, and doesn't fill the entire array. What am I missing that does this?
Here's itemGen():
private int itemGen(){
switch(biome){
case 0: return (int)(5*Math.random());
case 1: return (int)(5*Math.random())+5;
case 2: return (int)(5*Math.random())+10;
case 3: return (int)(5*Math.random())+15;
case 4: return (int)(5*Math.random())+20;
default: return 100;
}
}
Here's the code I'm checking the entries with:
public class main {
public static void main(String[] args) {
Cell c = new Cell();
System.out.println(Arrays.toString(c.rawCell()));
}
}
Here's the complete code of my Cell class:
import java.util.Arrays;
public class Cell {
private int[][] cell;
private int biome;
public Cell(){
this.cell = cellGen();
this.biome = biomeGen();
}
private int itemGen() {
switch(biome) {
case 0:
return (int)(5*Math.random());
case 1:
return (int)(5*Math.random())+5;
case 2:
return (int)(5*Math.random())+10;
case 3:
return (int)(5*Math.random())+15;
case 4:
return (int)(5*Math.random())+20;
default:
return 100;
}
}
private int biomeGen() {
return (int)(5*Math.random());
}
private int[][] cellGen() {
int[][] tempMap = new int[128][128];
for(int x = 0;x<128;x++) {
for(int y = 0;y<128;y++) {
tempMap[y][x] = itemGen();
}
}
return tempMap;
}
public int[][] rawCell() {
return cell;
}
public String toString(){
return Arrays.toString(cell);
}
}
There are two problems with this loop first you have the condition set incorrectly. x < 127 and y < 127. It should be x < 128 and y < 128 or more generally and correctly x < tempMap.length and y < tempMap[i].length:
private int[][] cellGen(){
int[][] tempMap = new int[128][128];
for(int x = 0;x<tempMap.length;x++){ //loop over rows x is the row number
for(int y = 0;y<tempMap[i].length;y++){ //loop over columns y is the column number
tempMap[x][y] = itemGen();
}
}
return tempMap;
}
for (int x = 0; x < 128; x++) {
for (int y = 0; y < 128; y++) {
tempMap[x][y] = itemGen();
}
}
try this
I am not sure that < 127 was right i think you wanted < 128
Also tempMap[y][x] = itemGen(); seems counter intuitive, unless otherwise needed perhaps you should do tempMap[x][y] = itemGen();
Right now you are filling a whole column before moving to the next column, where as it seems more intuitive to fill a whole row, before moving on to the next row.
Finally it makes sense to move the int y = 0 to inside the for loop like so for (int y = 0; y < 128; y++) as you are recreating y every time x iterates anyways.
otherwise you may do it like so
int x = 0;
int y = 0;
for (x = 0; x < 128; x++) {
for (y = 0; y < 128; y++) {
tempMap[x][y] = itemGen();
}
}
you can say it does not work, but having run this code
int[][] table = new int[128][128];
int x = 0;
int y = 0;
for (x = 0; x < 128; x++) {
for (y = 0; y < 128; y++) {
table[x][y] = 1;
}
}
for (x = 0; x < 128; x++) {
String line = "";
for (y = 0; y < 128; y++) {
line += ", " + table[x][y];
}
out.println(line);
}
I know that it does work.
Your code is working exactly the way you want it to - apart from your Cell.toString() method. If you have a look at that, you call Arrays.toString(int[][] cell), which will of course give you a string representation of the two(!)-dimensional array Cell.cell. Now, what's in a two dimensional array? A bunch of one dimensional arrays! So what your Cell.toString() method (as well as your test code) does is print the addresses of the arrays in Cell.cell, which are of course not at all what you want. You want a matrix representation of Cell.cell, and since Java 1.5, we have Arrays.deepToString(Object[] a) to do that for us. But that'll put all of the string in one line, and you probably want the output string for your square matrix to be square, so you'll have to iterate yourself. Here's code to compare outputs.
import java.util.Arrays;
public class main {
public static void main(String[] args) {
Cell c = new Cell();
int[][] cell = c.rawCell();
System.out.println("Arrays.toString:");
System.out.println(Arrays.toString(cell)); // ugly, ugly object addresses
System.out.println("\n\n");
System.out.println("Arrays.deepToString:");
System.out.println(Arrays.deepToString(cell)); // well this is basically alright, but it's all in one line
System.out.println("\n\n");
//now there's a pretty matrix! look at you, all filled with numbers
System.out.println("Going down the levels by hand:");
for(int i = 0; i < cell.length; i++) {
System.out.print("[");
for(int j = 0; j < cell[i].length; j++) {
System.out.print(cell[i][j]);
if(j != cell[i].length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
System.out.println("\n\n\n\n\n\n\n\n");
// if you're dead set on using Arrays.toString(),
// you'll have to go down to the very lowest level by hand
System.out.println("Arrays.toString for each one-dimensional array:");
for(int i = 0; i < cell.length; i++) {
System.out.println(Arrays.toString(cell[i]));
}
}
}
Now this wasn't really a difficult problem to figure out, except that it was way tougher than it should've been. There's a bunch of things you should take away from this:
Post ALL relevant code. That means all code that actually plays
any part in what comes out at your end that doesn't look the way it
should (and certainly the output statements if you see numbers with #
symbols in them, which should make you curious).
Please try not to make people ask multiple times. The very first comment was asking "is that the entire [..] code?" - that should not have to be repeated.
Look at the Javadocs of stuff you're using where you're not entirely, positively sure how they play along with your code if something doesn't work the way it should.
Actually check your output, don't just gloss over it - you will immediately see that there are # symbols in the output, and that never happens with ints.
I hope I'm not sounding too condescending, that is not the intention - to make this site work smoothly, communication is key. To become a better programmer, no one can do without attentiveness regarding their own code.
By mode, I am checking if the array has duplicates. I checked similar queries down here but they addressed the question with answers containing ArrayList and HashMap. I am not familiar with them and trying to answer it with an array. My following code only works for 1 duplicate and unable to perform multiple duplicate detection.
public class Mode {
public static void main(String[] args) {
int[] num = {2,3,4,5,8,8,8,7,7,7};
int mode = mode(num);
System.out.println(mode);
}
public static int mode(int[] num){
for(int x=0; x < num.length; x++){
for(int y=x+1; y < num.length; y++){
if(num[x] == num[y]){
return num[x];
}
}
}
return num[0];
}
}
The method mode should return a HashSet that contains the duplicates and not an int. Also note that your inner loop is incorrect. You should do:
public static HashSet<Integer> mode(int[] num){
HashSet<Integer> dup = new HashSet<>();
for(int x=0; x < num.length; x++) {
for(int y=0; y < num.length; y++) {
if(num[x] == num[y] && x != y) {
dup.add(num[x]);
}
}
}
return dup;
}
This solution is O(n2). You can achieve a better solution if you:
Sort the array.
Travel on it (only one time), if num[i] == num[i + 1], it's a duplicate.
This solution is O(n*log(n)) - Sorting and traveling on the array only once.
If you want a list of all of the duplicates, this code will give you the answer. If you want just the numbers that are duplicated use the code from #Stefan.
import java.util.Arrays;
public class Mode {
public static void main(String[] args) {
int[] num = {2, 3, 4, 5, 8, 8, 8, 7, 7, 7};
int[] mode = mode(num);
int i;
System.out.print("The duplicates are: ");
for (i = 0; i < mode.length - 1; i++) {
System.out.print(mode[i] + ", ");
}
System.out.println(mode[i] + ".");
}
public static int[] mode(int[] num) {
int numberOfDuplicates = 0;
int[] duplicates = new int[num.length];
Arrays.sort(num);
for (int i = 1; i < num.length; i++) {
if (num[i - 1] == num[i]) {
duplicates[numberOfDuplicates++] = num[i];
}
}
return Arrays.copyOf(duplicates, numberOfDuplicates);
}
}
You need to return HashSet OR LinkedHashSet for mode method instead of single int.
The first for statement is INCORRECT. It must be
for (int x=0; x < num.length - 1; x++) //--- You used x < num.length
The source code can be like below
Set<Integer> result = new HashSet<Integer>();
for(int x=0; x < num.length - 1; x++) {
boolean duplicated = false;
for(int y=x+1; y < num.length; y++) {
if(num[x] == num[y]) {
duplicated = true;
break;
}
}
if (duplicated) result.add(num[x]);
}
return result;
this is my 1st time asking for help for programming. Anywho, I need to write a program which find the determinant of a matrix (The determinant code will be made on a later date). Problem being is that I am having trouble getting my matrix to display. It seems that I have the array written correctly, but the output would skip the for loops to write the matrix. Would there be any changes that needs to be done or if theres a certain way that I need to set my array to determine determinants?
public class DetProg {
public static void main(String[] args) {
Scanner a = new Scanner (System.in);
Random mNum = new Random();
System.out.print("Enter matrix size: ");
int num = a.nextInt();
int numX = num;
int numY = num;
int [][] matNN = new int [numX] [numY];
int det = 0;// 0 is the placeholder until det method is inputted.
int n = mNum.nextInt(100)+1;
if (num >= 2)
{
for(int x = 0; x >= numX; x++)
{
for(int y = 0; y >= numY; y++)
{
matNN [x][y] = n;
System.out.println(matNN[x][y] + " ");
}
}
System.out.println("\n");
System.out.println("Determinant of a matrix is " + det);
}
else
System.out.println("Incorrect matrix size. Exiting...");
}
}
In your loops, you are making mistake in placing condition. you wrote x >= numX and y >= numY which will not be satisfied to even start the loop, because your x and y are equal to 0 in the start. it should be as:
for(int x = 0; x <= numX; x++)
{
for(int y = 0; y <= numY; y++)
{
Firstly you need to change your loop conditions.
for (int x = 0; x < numX; x++) {
for (int y = 0; y < numY; y++) {
this will result in proper assignment of values in an array and after this you can proceed further for your code of Determinant of a matrix.
I looked at the code over and over but I can't seem to get rid of this error. What am I doing wrong? I'm getting an error at the line I bolded.
import java.util.Scanner;
import java.math.*;
public class HW1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The numbers for n are not relevant
System.out.println("Please enter a number for the length of n.");
int n = input.nextInt();
// Creates an array with n values
int[] vectorArray = new int[n];
// Inputs random numbers into the array ranging from -100 to 100.
int dummy;
int temp = 0;
// Loop to generate negative and positive numbers into the array
for (int i = 0; i <= n; i++) {
dummy = (int)(Math.random()*2);
if (dummy == 0) {
temp = -1;
} else {
temp = 1;
}
**vectorArray[i] = ((int)(Math.random()*101)) * temp;**
System.out.println(vectorArray[i]); }
// Algorithm 1 - Brute force O(n^3)
int max = -1;
int sum;
}
}
}
You are accessing position n+1 in the array which is out of bounds.
Try changing the following line:
for (int i = 0; i <= n; i++)
To:
for (int i = 0; i < n; i++)
In general, I think its recommended to do something like this in case n ever changes after the array is initialized, and its more obvious what your code is doing (plus you'll never have to worry about this kind of Exception again):
for (int i = 0; i < vectorArray.length; i++)