Weird behaviour as I try to print a char array in Java - java

I declared a 2D char array and it is uninitialized. When I am trying to print the element in console(I am using eclipse) using a nested loop it does not print anything from the array and that is ok because it is filled with null. But, the weird part is I am not able to print anything in the outer loop as well. Not only that the println() statement immediately after the outer loop block does not print anything. The next one works. Here is the code,
private char oceanMap[][] = new char[10][10];
private void showOceanMap() {
System.out.println(" 0 1 2 3 4 5 6 7 8 9 ");
int c = 0, r = 0;
for(int i=0; i<10; i++) {
r++;
System.out.println("Hey");
for(int j=0; j<10; j++){
c++;
System.out.print(this.oceanMap[i][j]+"-");
}
//s+="|"+Integer.toString(i);
}
System.out.println(" 0 1 2 3 4 5 6 ");
System.out.println(" 0 1 2 3 4 5 6 7 8 9 ");
System.out.println("r = "+r+" and c = "+c);
}
When I call the method showOceanMap() it gives the following output:
The same code when running in jdoodle is working as expected.
when I initialize the array then it works fine in both ides. That imply that it is because of initialization issue, but why would the other println() statements wont work? I am not getting any exception or error.
An explanation would be helpful.

Related

How to compare two consective numbers of an array in java

I am trying to compare two consecutive numbers of an array and print the largest one in every iteration. I have written below code but its giving unexpected responses. Can somebody please check and help me understand the mistake.
PS: I just started learning java.
public class Test {
public static void main(String [] args){
int[] list = {6,0,4,2,9};
int current;
for(int j=0; j<list.length-1; j++){
if(list[j]>list[j+1]){
current = j;
}else{
current = j+1;
}
System.out.print(current + " ");
}
}
}
Expected response: 6 4 4 9
Actual response: 0 2 2 4
Ok so your code is just returning j which here is used as the number in youy for loop.
In your if you're using j as an index to get the value in list matching that index; but in the rest of your for loop you're setting current to the value of j and not the value of list at the index j.
What you'll want to print is the value of list[j] and not j.
In fact, if you look closely [0 2 2 4] are the indexes of [6 4 4 9]

Java: Unable to understand for loop behaviour

I am slightly new to coding, I am solving a problem which should print all the integers between variables L and R including L,R. but I am getting the required output repeatedly. I don't understand the reason for it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int L = sc.nextInt();
int R = sc.nextInt();
for (int i = 0; ; i++) {
if (i >= L && i <= R) {
System.out.print(i + " ");
}
}
}
Input: L=4 ,R=8
Output: 4 5 6 7 8 4 5 6 7 8 4 5 6 7 8 and so on...
You put the condition is the wrong place, so your loop is infinite.
To further explain, since your loop has no exit condition, i will be incremented forever, but after reaching Integer.MAX_VALUE, the next i++ will overflow, so i will become negative (Integer.MIN_VALUE). Then it will continue to increment until it reaches again the range you wish to print, so that range will be printed again and again, forever.
The correct loop should be:
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
Now i will start at the first value you wish to print (L), and the loop will terminate after printing the last value you wish to print (R).
If are new to coding then follow this link to understand how for loop works
And you are not defining any condition when for loop should stop executing the code block
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
This is how your for loop should be

How to initiate a falling element effect in a 2D array in java? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am creating a basic connect 4 game in java.
For this I have created a 2d array, board[][] of size 8 * 8.
To make it look a decent game, I want to make it seem as if the player tokens
fall through the column to the space just above the occupied grid.
However, the code that I have written generates an ArrayIndexOutOfBoundsException. Please check the code below and tell me where I must be going wrong.
int a[] = {0,0,0,0,0,0,0,0};//stores the no. of empty space in each column
char board[][] = new char [8][8];
System.out.println("\n >>>-\\/->>> ENTER THE COLUMN NUMBER : PLAYER "+current_player+" :PLAYER TOKEN :"+current_player_token);
colno=Integer.parseInt(br.readLine());
tmp=a[colno-1];
//this will do the printing and initiate the falling effect only till the time required
for (k=0 ; k<7-tmp ; k++ )//k here represents the loop control variable that determines how long the element will seem to fall until it reaches the empty space
{
System.out.print("\f");
System.out.println(" 1 2 3 4 5 6 7 8 -COLUMN");
for( i=0 ; i<8 ; i++ )
{
System.out.print(" ");
for( k=1;k<=9;k++)
System.out.print("---------");
System.out.println();
System.out.println();
System.out.print(" |");
for ( j=0 ; j<8 ; j++ )
{
System.out.print(" "+board[i][j]+" |");
}
System.out.println();
System.out.println();
}
System.out.print(" ");
for(k=1;k<=9;k++)
System.out.print("---------");
//the lines below generates an ArrayIndexOutOfBoundsException
board[k][colno-1]=current_player_token;
if(k!=0)
{
board[k-1][colno-1]=' ';
}
The Exception is generated at the line :
board[k][colno-1]=current_player_token;
Cause your for-loop start with k = 1 and end with k = 8. But your board has a size of 8, so indexes goes from 0 to 7. When you call board[8] it fails.

java.util.NoSuchElementException for reading in integer.txt

I'm creating a program that receives a 6x7 list of integers and stores then in an array. However I'm getting a java.util.NoSuchElementException, I've been out of practice for a while so I may be sloppy with my syntax and I'm wondering what I am doing wrong.
This is an example of a .txt file being read.
0 1 0 3 1 6 1
0 1 6 8 6 0 1
5 5 2 1 8 2 9
6 5 6 1 1 9 1
1 5 6 1 4 0 7
3 5 3 4 4 0 7
my code
public static void main(String[] args) throws FileNotFoundException
{
System.out.println(new File("num1.txt").getAbsolutePath());
int i;
int j;
i=0;
j=0;
int [][]connect4Array;
connect4Array= new int [6][7];
int [][]list;
Scanner readFile = new Scanner(new File("num1.txt"));
while(readFile.hasNextInt())
{
for(i=0;i<5;i++)
{
connect4Array[i][j]=readFile.nextInt();
for(j=0;j<6;j++)
{
connect4Array[i][j]=readFile.nextInt();
}
}
}
System.out.println(connect4Array[1][2]);
list=connect4Array;
isConsecutiveFour(list);
readFile.close();
}
list=connect4Array;
isConsecutiveFour(list);
readFile.close();
}
public static boolean isConsecutiveFour(int[][] values) throws FileNotFoundException
{
boolean connected4;
connected4=false;
int cntr1;
int cntr2;
cntr1=0;
cntr2=0;
int i;
int horizontalMatch;
int verticalMatch;
int diagonalMatch;
horizontalMatch=0;
i=0;
//check for horizontal matches
for(cntr1=0;cntr1<6;cntr1++)
{
for(cntr2=0;cntr2<7;cntr2++)
{
if(values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
connected4=true;
horizontalMatch=+1;
}
}
}
}
}
}
System.out.println(connected4);
System.out.println("Horizontal Matches= "+horizontalMatch);
return(connected4);
}
the full error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at assignment5.Assignment5.isConsecutiveFour(Assignment5.java:90)
at assignment5.Assignment5.main(Assignment5.java:49)
edit:
I wasn't planning on sharing the rest of my code, but after fixing the error in the for loop, it noticed another in a different part of my code with the same error. If you guys could help again that'd be great
Each time through the outer loop, you're reading 35 values, because you're iterating the second loop 5 times, and each iteration reads one value, then iterates the third loop 6 times. And you have 42 values in the file. So you're finishing the file partway through the second iteration of the outer loop, then getting the error when you're trying to read the 43rd value.
You probably don't need the outer loop at all, or the first line inside the second loop. The following may do what you want. Notice how I've changed the termination conditions on each loop, to accommodate your 6 rows and 7 columns.
for (i = 0; i < 6; i++) {
for ( j = 0; j < 7; j++){
connect4Array[i][j]=readFile.nextInt();
}
}
the problem is with connect4Array[i][j]=readFile.nextInt(); in outer loop which the value of j at there is always 0 as you defined before loops but in inner loop it'll get the value of j defined in for statement also you need to increase the borders (i and j):
for(i=0;i<=5;i++)
{
for(j=0;j<=6;j++)
{
connect4Array[i][j]=readFile.nextInt();
}
}

Histogram project: code throws ArrayIndexOutOfBoundsException

This is the code I've isolated:
public static void randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}
scoreHist(a);
}
public static void scoreHist(int[] scores) {
int[] counts = new int[30];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}
}
But whenever I run this, it gives me this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (Insert Random # Here)
at arrayhistogram.ArrayHistogram.scoreHist(ArrayHistogram.java:39)
at arrayhistogram.ArrayHistogram.randomIntArray(ArrayHistogram.java:31)
at arrayhistogram.ArrayHistogram.main(ArrayHistogram.java:21)
I'm lost with this. Ideas? I'm really stuck and have been going in circles with this for a while now.
int index = scores[i];
counts[index]++;
according to the randomInt (-5,15), it's possible the index can be negative.
Change
counts[index]
to
counts[index + 5]
This is because index comes from the a array whose elements are initialized to values between -5 and 14 inclusive. However only values between 0 and 29 inclusive are allowed as indices to counts, hence you need to add 5.
So this is the stuff that your code does :
You pick 'n' random numbers from -5 to 15 ( say n=5 ), push them into an array
Say, the array becomes
scores[] = {0,1,1,5,-3}
Now, you are passing this created array in the scoreHist().
Now, see the state of variables during run time
i scores[i] index counts[index]
--- --------- ----- ----------------------
//1st iteration
0 scores[0]=0 0 counts[0]=counts[0]+1 -> 1
Everything goes fine in the first iteration.
//2nd iteration
1 scores[1]=1 1 counts[1]=counts[1]+1 -> 1
Everything goes fine here as well. Now "counts[] = {1,1}"
//3rd iteration
2 scores[2]=1 1 counts[1]=counts[1]+1 -> 2
Things go alright. counts[1] has been updated. Now "counts[] = {1,2}"
//4th iteration
3 scores[3]=5 5 counts[5]=counts[5]+1 -> 1
Things go absolutely fine here .
//5th iteration
4 scores[4]=-3 -3 counts[-3] !!!!!!!! It is out of bound limits for the
array. This index does not exist.
This is what causes the exception that you have
Hope this helps.

Categories

Resources