I am a beginner to Java--I want to construct a 2D array that takes votes as a user's input. I've been trying to make sure the user cannot enter "votes" for themself--I have tried using
&& col != row
In the for loop but this does not seem to work. My current for loop is this:
for (int row = 0; row < Vote.length; row++)
{
System.out.println("Enter "+ this.TeamMember[row]+"'s votes, points must add up to 100:");
System.out.println();
for (int col=0; col < this.Vote[row].length && col != row; col++ )
{
System.out.println("Enter "+this.TeamMember[row]+ "'s points for "+ this.TeamMember[col]+":");
this.Vote[row][col] = scan.nextInt();
}
Is there a way to skip data entries for when the row in a two-dimensional array equals the column?
Thanks for your help!
Try putting that condition inside the inner for loop
if(row != col){
// inner for loop
}
You can use an if-conditional and a continue statement to skip the current iteration of the for loop.
Inside your inner for loop, immediately check if (col == row), and if so, continue;.
EDIT: You should also take out the && col != row conditional in the inner for loop. That will kill your for loop early.
Related
Ok everyone i'm taking a free course on EDX and I can't get some of the activities earlier In lesson to work so I had to dive head first into this.
The program creates a "zig zag" pattern, the size of which depending on the int numTiles. I am confused by this because running through the program in my head I think it would way work waaay differently. I don't know why it prints 1 for the entire line depending on the numTiles. Wouldn't the program stop at the point? Why don't J and I increase everytime? What case would be the spaces? Do I or J ever go over the int numtiles? How does J ever equal 0 except in the first time it runs? Please help me wrap my head around this.
public class Main {
public static void main(String[] args) {
int numTiles = 8;
for(int i=0; i<numTiles;i++){
for(int j=0; j<numTiles;j++){
if(i%2==0){
System.out.print("1");
}else if ((i-1)%4==0 && j==numTiles-1){
System.out.print("1");
}else if((i+1)%4==0 && j==0){
System.out.print("1");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
I think your misunderstanding may boil down to vague variable names and difficult-to-read code style. Here's how I would translate the program into a more understandable form:
public class Main {
public static void main(String[] args) {
int rows = 8;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < rows; col++) {
if (row % 2 == 0 ||
row % 4 == 3 && col == 0 ||
row % 4 == 1 && col == rows - 1) {
System.out.print("1");
}
else {
System.out.print(" ");
}
try { Thread.sleep(100); } // for demonstration purposes
catch (Exception e) {}
}
System.out.println();
}
}
}
The outer loop controls the printing of the rows. There will be 8 rows in the output in this case. The inner loop controls printing of the columns (also 8). Cells are printed left to right in each row.
Now, the only question left is for each cell, do we print a "1" or a blank space? The conditional says print a "1" if the row is an even number OR if the row is an odd number and the current column index is at one end or another. Otherwise, print a space.
I also added a Thread.sleep call which will delay printing, allowing you to watch the program run cell by cell. I hope this helps clarify matters for you.
I am reading in a file in which each row has a column no, row number, detail. The file is sorted on column then row. I want to place the detail in a csv file in the correct row and column. So I am testing for change in row number and then add in line breaks ("\n").
The issue is that the System.out.println on each side of the for loop is being displayed in the log; however, the loop its self is not triggered (i.e., the line break is not added and the System.out.println is not appearing in the log.
The code is:
System.out.println("New row - " + Integer.parseInt(report.getReportDetailRow())+ " greater than current row - " + currentRow);
currentCol = 0;
//Add line breaks
int j = Integer.parseInt(report.getReportDetailRow());
for(int i = currentRow; i > j; i++){
System.out.println("Append line break");
fileContent.append("\n");
}
System.out.println("After append");
currentRow = Integer.parseInt(report.getReportDetailRow());
if (currentCol == Integer.parseInt(report.getReportDetailColumn())){
fileContent.append(report.getReportDetailDetails() + ",");
currentCol++;
}else{
//Add columns
for(int i = currentCol; i == Integer.parseInt(report.getReportDetailColumn()); i++){
fileContent.append(",");
}
fileContent.append(report.getReportDetailDetails() + ",");
currentCol = Integer.parseInt(report.getReportDetailColumn());
}
Please note that I have use "i > j" instead of "i == j" to try to force a result.
In your statement for iterating through the rows, you have
for(int i = currentRow; i > j; i++)
If j is the number of current rows, then you need to change your condition to i < j to go through them all.
for(int i = currentRow; i > j; i++) {
System.out.println("Append line break");
fileContent.append("\n");
}
The loop above would either result in an infinite loop or never get triggered(your case)
Infinite if i is already greater than j. It would never terminate with i++ for every iteration
Never execute if i is less than j, since the condition states i>j.
You might want to change the conditional statement inside the loop to correct this to either i==j or i<j
for(int i = currentRow; i == j; i++) // in which case replacing this with an `if(i==j)` would do the needful
or
for(int i = currentRow; i < j; i++) // to iterare from initial i upto j
(UPDATED)
I'm having trouble figuring out what to do here, i need to compare a 2d array that to see if any of the numbers match. I need four numbers to match either up/down, left/right, or diagonal. I just can't get it to test for the down/left diagonal ( / ) here is my updated code
public static boolean isAdjacentFour( int[][] a ) {
// Code to test if column has four adjacent numbers
for ( int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length - 1 ; col++) {
if (a[row][col] == a[row+1][col] && a[row+2][col] == a[row][col]
&& a[row+3][col] == a[row][col]) {
return true;
}
}
}
// Code to test if row has four adjacent numbers
for ( int row = 0; row <= a.length - 1 ; row++) {
for (int col = 0; col <= a[0].length - 3 ; col++) {
if (a[row][col] == a[row][col+1] && a[row][col] == a[row][col+2]
&& a[row][col] == a[row][col+3]) {
return true;
}
}
}
// Code to test if there are 4 adjacent numbers in a down/right ( \ )diagonal
for ( int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length - 3 ; col++) {
if (a[row][col] == a[row+1][col+1] && a[row][col] == a[row+2][col+2]
&& a[row][col] == a[row+3][col+3] ) {
return true;
}
}
}
for ( int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length + 3 ; col--) {
if (a[row][col] == a[row+1][col-1] && a[row][col] == a[row+2][col-2]
&& a[row][col] == a[row+3][col-3] ) {
return true;
}
}
}
return false;
}
Well one problem I noticed in the first nested for loop is this line of code,
for ( int row = 0; row <= a.length - 3 ; row++)
The way you have it now, the row variable is going to be incremented with each iteration of the outer for loop. However, with how you're executing your program, the condition should be row <= a.length - 4 and here's why. Suppose you had a four by four 2D array. The nested for loop will go through one normal iteration of the inner loop, which actually checks every single column for possible matches of four consecutive matching numbers in a column. Here's what it looks like when actually running the program starting at the outer for loop and row = 0,
Iteration One of the inner for loop:
if (a[0][0] == a[1][0] && a[2][0] == a[0][0] && a[3][0] == a[0][0])
Iteration Two of the inner for loop:
if (a[0][1] == a[1][1] && a[2][1] == a[0][1] && a[3][1] == a[0][1])
Iteration Three of the inner for loop:
if (a[0][2] == a[1][2] && a[2][2] == a[0][2] && a[3][2] == a[0][2])
Last Iteration of the inner for loop:
if (a[0][0] == a[1][3] && a[2][3] == a[0][3] && a[3][0] == a[0][3])
Once this is done, the row variable will be incremented according to the outer loop definition. This is what is most likely causing an error because now as we start iterating through the inner loop with row = 1, this happens
Iteration One of the inner for loop:
if (a[1][0] == a[2][0] && a[3][0] == a[1][0] && a[4][0] == a[1][0])
Here, we already have an indexoutofboundsexception when trying to access the 5th row in a 4x4 2D array. So the simple fix here is to change
for(int row = 0; row <= a.length - 3 ; row++)
to
for(int row = 0; row <= a.length - 4 ; row++)`
A similar argument can be made for the second nested for loop. If you don't believe me, do something similar to what I did for the rows and write out the iterations for it using a 4x4 2D array. You'll get the arrayindexoutofbounds exception in the first iteration of the outer for loop and in the second iteration of the inner for loop when row = 0 and col = 1, causing the program to make a check at the fifth column in the first row of a 2D array. So the simple fix should be to change
for (int col = 0; col <= a[0].length - 3 ; col++)
to
for (int col = 0; col <= a[row].length - 4 ; col++)
Personally, I prefer to use a[row].length only because there could be some instances where it's not a perfect nxn 2D array. For example, some rows may have only 3 columns where the first row has 7 columns. If this is the case, then you'll get an outofbounds exception for trying to access columns that exist in the first row that don't exist in other rows.
For the third nested for loop, again, same argument can be made just by writing out the iterations and it should be changed to
for(int row = 0; row <= a.length - 4 ; row++) {
for(int col = 0; col <= a[row].length - 4 ; col++)
The last nested for loop has a logic problem pertaining to the inner for loop. Since you're decrementing from 0, you're going to get an out of bounds exception just from trying to access negative indices in the array. So the simple fix should be to initialize col to the last column and change the condition to col being greater than or equal to 3 since you're accessing elements at the columns, col, col-1, col-2, and col-3. If that is confusing, think about it this way. You're checking columns starting from col and the three that come before it. What if there aren't even four columns to begin with? This is why there's the condition col >= 3 because you check a column and the three that come before it until you've reached column #4 (col = 3). Once you've reached column #3 (col = 2), there's no way of checking that column and the three before because there are only 3 columns to check at this point. Changes similar to the other 3 nested loops should be made to for ( int row = 0; row <= a.length - 3 ; row++) regarding the -3. It should end up looking like this,
for ( int row = 0; row <= a.length - 4 ; row++) {
for (int col = a[row].length - 1; col >= 3; col--)
As a rule of thumb , always put debug points to see why you are getting exception/error.
The issue here is your outer loop runs from 0 to row-1 . But inside in inner loop you are using [row+2] and [row+3] and [row+1] . Now when the outer loop goes to row-2 iteration , you will get a out of bound exception.
Can post the code here , but if you understand this , you should be able to solve it.
(EDIT) : example as asked in comment.
assume you have a 2D array A[][]of size 10X10 .
Now if the current loop is at A[4][4] or (A[row][col]) :
left element : A[4][3] or (A[row][col-1]) // here we are at same row but (column -1) as we want the left element.
top-right element : A[3][5] or ((A[row-1][col+1]) // here we are going to (4-1) row as we are interested in above row and (4+1)column as we want right element.
bottom-left: A[5][3] (A[row+1][col-1]) ...
Now the two consecutive bottom-left elements will be (A[row+1][col-1]) and (A[row+2][col-2]).
Try visualizing it by drawing a 2D array and naming each cell in terms of A[i][j].
I want to add data to a dataset to display some values on a graph. On some files, the first line is a description of the columns (like "Timestamp" or something else). I need my code to test if the first line contains integer or float values and if not to skip this line and add data to dataset from 2nd line.
This is my code:
for (int i = 0; i < listOfLists.size(); i++) {
for (int j = 1; j < listOfLists.get(i).size(); j++) {
if (listOfLists.get(i).get(0).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(0).matches("\\d+(?:\\.\\d+)?")) {
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
} else if(listOfLists.get(i).get(1).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(1).matches("\\d+(?:\\.\\d+)?")){
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
The problem is that I get an error when he's trying to represent String on the plot of the bar chart
List of lists is a list of columns. Each column of the file is added into a list and each list into the listOfLists.
I tried to use on the else if block: listOfLists.get(i).remove(0) but it didn't worked. (in next loops it keeped removing the first line of the remaining list.
Thanks in advance!
You can check in the outer loop, before inner loop:
if (i == 0 && listOfLists.get(i).get(0).matches(/\\d+(?:[\\.,]\\d+)?)/) == false) {
continue; // skip first line
}
BTW: You should not call remove method while iterating list because you will get ConcurrentModificationException.
It could be something like this:
for (int i = 0; i < listOfLists.size(); i++) {
for (int j = 0; j < listOfLists.get(i).size(); j++) {
if (j==0){ // Only test if it is a string in position [0]
boolean isNumber = listOfLists.get(i).get(0).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(0).matches("\\d+(?:\\.\\d+)?");
if (!isNumber) continue; // If it is not a number, skip it
}
// Add to database, because it is a number
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
Hope it will help anyone to understand.
for(int i = 0; i < n; i++){ /* i = 0 means position of i is 0 which is 1st line */
if(i != 0 ){ /* and as our purpose is skipping first line so I will only continue when i is not equal 0 like this we can skip first line in this if block */
continue;
}
}
I am trying to iterate through a randomly generated 2d array of 0s, and 1s. In this method which I am stuck on I am trying to see if the subdiagonal has all the same numbers, all 1s, all 0s, or different numbers.
sub diagonal meaning:
110
101
011
The 0s are the subdiagonal.
this is the code I have as of now. I am trying to iterate starting at the last row and counting up to the first row diagonally.
int firstValue= matrix[matrix.length-1][0];
int result = -1;
for(int row = matrix.length-1; row > 0; row--)
{
int column = row;
if(firstValue == matrix[row][column])
{
result = firstValue;
continue;
}
else
{
result = -1;
break;
}
}
if(result== 1)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else if (result == 0)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else
{
System.out.println("Numbers on subdiagonal are different");
}
}
I'm almost certain my issue is with the firstValue and/or the for loop counting up the diagonal.
Any help would be appreciated, thanks much
Your issue seems to be at the following line,
for(int row = matrix.length-1; row > 0; row++) {
...
}
you are doing a
row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length
Then you will be accessing a index that does not exist causing a ArrayIndexOutOfBoundsException
Edit
what you'd want to do is,
for(int row = matrix.length-1; row >= 0; row--) {
....
}
This way you'd be able to iterate though your array from largest index to the smallest (0).
Edit 2
Let's say Staring array called arr has 4 elements. It'll be structured as below,
arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";
Array indexes always starts from 0, so the highest index in the above array is 3.
So if you want to iterate from smallest index to the largest, you'd do
for(int i = 0; i < arr.length; i++) {
//i's initial value is 0 and itll increment each time the loop runs
//loop will terminate when i is no longer < 4
System.out.println(arr[i]);
}
and to iterate through the array in reverse order you'd do,
for(int i = (arr.length - 1); i <= 0; i--) {
//i's initial value is (4 - 1) and it'll decrement each time the loop runs
//loop will terminate when i smaller or equal to 0
System.out.println(arr[i]);
}
So we want to check if all of the values in the subdiagonal are the same value, and if they are then we want to print the value that is the same. First we set aside a comparison to check the other indices
int checkValue = arr[0][arr[0].length-1];
This is the last value in the first row. Then we set a flag to catch whenever our index that we are checking matches our first value. We'll set it to false because we'll assume that the values don't match.
boolean flag = false;
Now that we have that, we need to iterate through each row in our array. We will start with the second row (arr[1]) and then we need to check the value one down and one over compared to the last value we checked (arr[1][arr.length - 1 - i]). If our first value (we assigned it's value to checkValue) and the value we are checking are the same, change the flag to true.
for (int i = 1; i < arr.length; i++)
if (arr[i][arr.length - 1 - i] != checkValue)
flag = true;
That'll run through all of the rows in the array. Now we have to check the state of our flag and print out the appropriate response. If the flag is true, print out that the values on the row are the same. Else we will say that the subdiagonal does not match all the way through.
if (!flag)//remember our flag is set to false, double negative equals true.
System.out.println("All of the values on the subdiagonal are the same");
else
System.out.println("All of the values on the subdiagonal are not the same");