System.out.println() changes value of a variable in single threaded program - java

I have been working an a good size but single threaded java application. In it I have a function which loops through a matrix of about size[300][10]. I have done a lot of things above this code snippet and have 3 other matrices of similar sizes as local variables. I was having problems with the loop not going through the first value (table[0][0]) when I noticed that the code:
System.out.println("");
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if(i == 0 && j == 0){System.out.println("looped through 0 0");}
// a bunch of other stuff
}
}
prints out:
looped through 0 0
but the code:
//System.out.println("");
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if(i == 0 && j == 0){System.out.println("looped through 0 0");}
// a bunch of other stuff
}
}
does not print anything.
Why would this be? Have I run out of Java heap space? Have I overflowed? Is this a compiler error?

I found what was wrong. Above the loop I had another loop and had left a printf statement in there. I am still not sure why this occurs but I was able to reproduce it in the following class.
public class TestJavaPrintfError {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.printf(" ");
}
String[][] table = new String[300][6];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (i == 0 && j == 0) {
System.out.println("looped through 0 0");
}
}
}
}
}
I am on developing on eclipse neon. Anyone know why this happens?

Is that a joke?
Just scroll the console to the rightmost, you will see the print.
You are using System.out.printf(" "); 100 times, it output alot of spaces and push your pritnt to the right.

Related

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

Why can't variable j initialization be in the termination expression of the for loop?

public class Gameboard
{
public char[][] board;
public static void main(String args[])
{
Gameboard blank = new Gameboard(false);
System.out.println("Printing blank gameboard:\n" + blank + "\n");
}
public Gameboard(boolean setup)
{
char[][] board = new char[8][8];
if (!setup)
{
for(int i = 0; i < board.length;i++)
{
for(int j = 0; j < board[j].length;j++)//critical condition
{
board[i][j] = '-';
}
}
}
}
}
I know that column length is being used not the row length but the 2d array has the same length row-wise and column-wise.
your logic is off here, since i counts through the first dimension and j through the second: what you really wanted was
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
board[i][j] = '-';
}
}
this issue of course was in the following line:
for (int j = 0; j < board[j].length; j++)
You are using j as the index on the first dimension of the board array but defining it as a value which goes up to a maximum length equal to the length of the second dimension. Which of course opens you up to the chance of having an index out of range, which is exactly what this code produces.
The reason you have a problem despite the fact that both dimensions are the same is because the conditional for the for loop to exit reevaluates each loop.
The logic is:
j < board[j].length
So at 7 you get:
7 < board[7].length
which is the same as:
7 < 8
Great it passes so goes through another loop but what happens at 8?
8 < board[8].length
Well 8 is out of bounds for the board array so it throws an exception, it simply cant evaluate it. the variable i however never reaches 8, it stops at 7, so you never get an index out of bounds in that case.
If you did the following it would work (but bad practice):
for(int j = 0; j < board[0].length; j++)

Is it possible to add conditional for loop in nested ones?

In an ordinary nested for-loop, is it possible to put a condition to determine whether to run a specific for loop in a nested loop?
For example, in a code like below, is it possible to skip second for-statement(int j) when int i of the first loop is < 3?
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
so that only when i < 3, the actual executed code looks like this?
for(int i = 0; i < 5; i++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
The reason why I want to do this is that the inner-most codes are quite long as well as the number of the for loops (about 10 nested), and really don't want to repeat them again. I can think of doing this with methods, but I am not quite familiar with methods and OO programming.
Much appreciated,
Generally, I'd probably extract the code to a separate method. But here's a workaround if you don't want to do that:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < (i < 3 ? 1 : 3); j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
This way, if i < 3, the j loop will only execute once.
The method approach would roughly look something like this:
void outer() {
for(int i = 0; i < 5; i++) {
if(i < 3) {
inner(i, 0);
} else {
for(int j = 0; j < 3; j++) {
inner(i, j);
}
}
}
}
void inner(int i, int j) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
You may want to make the methods static, or private, or remove the parameter(s), or add a return type, etc. It's hard to say with just the code in your question.

Find pattern in array of array

Hi guys I am currently learning Java and I'm trying to make a program that you can use too book motel rooms. I'm trying to create a method to search the amount of days a guest needs and then check the days and units that are free. I'm using a 2D array of an array of an array.
public void doSearch() {
this.redisplay();
int daysWanted = UI.askInt("Number of days required");
int days = 0;
for(int i = 0; i < NUM_UNITS; i++){
for(int j = 0; j < NUM_DAYS; j++){
if(bookings[i][j] == null){
days++;
if(daysWanted >= days && this.bookings[i] == this.bookings[i]){
this.displayCell (i, j, Color.red);
}
}
}
}
}
here is what the program looks like currently, and what i have shown above is the method i am trying to do. What my problem is, when i type in how many days, it checks if the available unit is free for that many days, but i want it to be consequtive. How would i go about this? any help is appreciated, thanks :)
change this :
for(int j = 0; j < NUM_DAYS; j++){
if(bookings[i][j] == null){
days++;
if(daysWanted >= days && this.bookings[i] == this.bookings[i]){
this.displayCell (i, j, Color.red);
}
}
}
to something like this:
days = 0;
int[] daysWeWant = new int[daysWanted];
for(int j = 0; j < NUM_DAYS; j++){
if(bookings[i][j] == null){
daysWeWant[days] = j;
days++;
if(daysWanted == days){
break;
}
}
else{
days = 0;
int[] daysWeWant = new int[daysWanted];
}
}
if(days== daysWanted ){
for(int j = 0 ; j< daysWanted; j++){
int day = daysWeWant [j];
this.displayCell (i, day , Color.red);
}
}
If you do this it makes days zero if one day is not avaiable and continue to search again.
I suspect Lrrr was on the right path - you need to reset your days counter for each unit that you are searching. Likely you can change:
int days = 0;
for(int i = 0; i < NUM_UNITS; i++){
for(int j = 0; j < NUM_DAYS; j++){
to
for(int i = 0; i < NUM_UNITS; i++){
int days = 0;
for(int j = 0; j < NUM_DAYS; j++){
But without sample data, it would be a bit of work to check for certain.
You might find that writing some unit tests would help you a lot in working on this.

Add to ListArray from Array

For an array, how can i take all the values at even indexes and add to nameArray and all the values at odd indexes and add to scoreArray? I got this code but it isn't working.
String[] inputArray = {"john", "10", "frank", "14"}
for (int j = 0; j == inputArray.length; j++) {
if ((j % 2) == 0) {
nameArr.add(inputArray[j]);
} else {
scoreArr.add(inputArray[j]);
}
}
You probably mean for (int j = 0; j < inputArray.length; j++)
j == inputArray.length is evaluated to false at the first iteration so your loop doesn't run.
However, you could get rid of the if statement (assuming that your inputArray always contains a name associated a score, i.e always contains pair values) :
for (int j = 0; j < inputArray.length; j+=2) {
nameArr.add(inputArray[j]);
scoreArr.add(inputArray[j+1]);
}
Or you could also use a Map<String, Integer> to associate each name with its corresponding score (assuming names are unique) :
for (int j = 0; j < inputArray.length; j+=2)
m.put(inputArray[j], Integer.parseInt(inputArray[j+1]));
You probably mean to have a < in your loop and not a == and also, try using inputArray and not split2[] like this:
for (int j = 0; j < inputArray.length; j++) {
if ((j % 2) == 0) {
nameArr.add(inputArray[j]);
} else {
scoreArr.add(inputArray[j]);
}
}
What you want to do is look through each element in the array, to do this you want to go through every element starting at 0 and ending at the lengthof the array -1 (because arrays are 0 indexed). Once you are in the loop you want to check if it is an even or odd number using the modulo operator.
for (int j = 0; j < inputArray.length; j++){
if ((j % 2) == 0) {
nameArr.add(inputArray[j];
} else {
scoreArr.add(inputArray[j];
}
}

Categories