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();
}
}
Related
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
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.
I know there is another thread with the same name, but the answer isn't really the one I'm looking for.
I can only use for loops. The other answer uses complex syntax like:
reverse = !reverse ? i == max : reverse;
i = reverse ? i-1 : i+1;
Can it be simpler than that?
Thanks a lot.
So, this is the output.
I can only get until 4 I don't know how to keep from there...
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1;i<=4;i++) {
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
for(int i=4;i>=1;i--){
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
}
}
but my output is the following:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
Hii have done using the below code
public class Test
{
public static void main(String args[]) {
int j,i;
int max=4;
int n=0;
for(i=0;i<((max*2)-1);i++)
{
if(i<max)
n++;
else
n--;
for(j=1;j<=n;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
The below is the outputYou can generalize it for any number i hope this is fine
Your two outer loops are:
for(int i=1;i<=4;i++) {
for(int i=4;i>=1;i--) {
This will generate the sequence 1, 2, 3, 4, 4, 3, 2, 1. If you want to only have one 4-length row in the output, change the second loop to:
for(int i=3;i>=1;i--) {
so that it starts from 3, instead of 4. The problem is that currently, both your outer loops generate the value 4 right after one another.
I have this code for insertion sort which is failing to give an output for a test case..
import java.io.*;
import java.util.*;
public class Solution {
public static void insertionSortPart2(int[] ar)
{
// Fill up the code for the required logic here
// Manipulate the array as required
// The code for Input/Output is already provided
int n =ar.length;
for(int i=1;i<n;i++)
{int k= ar[i];
int j=i-1;
while(ar[j]>k && j>-1)
{
ar[j+1]=ar[j];
j--;
}
ar[j+1]=k;
printArray(ar);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
The test case for which this does not return an output is
9 8 6 7 3 5 4 1 2
error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
I cannot figure out why..
It works correctly for 1 4 3 5 6 2
Issue is with your while loop and this is the line where you might be getting exception while(ar[j]>k && j>-1). You are trying to access array using negative index i.e. -1. You get this exception when you try to access elements outside of either lower or outer bound of an array.
When i is 1, j is 0 by j=i-1
You enter the while loop since a[1] > a[0] i.e. 9 > 8
You do j-- where value of j becomes -1
You come back to while (while(ar[j]>k && j>-1)) try to access a[j] ie.. a[-1] and hence you get ArrayOutOfBoudException.
You may need to check j > -1 before accessing array i.e. reverse your condition in while loop from
while(ar[j]>k && j>-1)
To
while(j>-1 && ar[j]>k)
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.