This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have to check if a sequence of any numbers are equals. The user will submit a sequence, and if, the numbers repeat in sequence, he won some points.
And the sequence to win the points it's a sequence of three. For example:
1 3 4 4 4 5
He won the points because he inputted a sequence of 3 numbers 4.
The sequence of numbers it's on a Vector. The size of the vector, It's given by the user too.
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Scanner sc1 = new Scanner(System.in);
R = sc1.nextInt();
int M[] = new int[R];
int L[] = new int[R];
for (int i = 0; i < M.length; i++) {
M[i] = sc1.nextInt();
}
for (int i = 0; i < L.length; i++) {
L[i] = sc1.nextInt();
}
//The problem It's here ************************************
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at maratona.Maratona2.main(Maratona2.java:37)
Java Result: 1
i < M.length
Now let's assume the length of the Vector you are saying is 5 ok?
Now my loop will run till i is less than 5, right?
Now go to your next code :
if (M[i] == M[i + 1] && M[i + 1] == M[i+2])
Let's take the value of i as
4 (suppose)
which is in fact less than 5 and the loop condition satisfies.
But see the next code, it becomes
M[4]==M[5]&& ==M[6]
Obviously since the length of the given Vector is 5, my last element's index will be 4.
So after that **5 & 6 ** will show null only.
That's why it's saying ArrayIndexOutOfBounds Exception error at 5.
Hope this helps!
your loop variable i must stop at m.length-3
(i <m. length-2)
to have i+1=m.length-2 and i+2=m.length-1
but in your case you are trying to access i+1=m.length and i+2= m.length+1 both are out of bounds on the last two iterations
As the others already said, u r overshooting the boundaries of your array. You need to stop the loop 2 earlier to prevent.
You possably want to use something like that:
int sequenceLength = 3;
for (int i = 0; i <= M.length - sequenceLength; i++) {
boolean correct = true;
for (int j = 0; j < sequenceLength && (correct = (M[i] == M[j+i])); j++);
if (correct){
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
break;
}
}
Related
I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
This question already has answers here:
Pascal's triangle positioning
(5 answers)
Closed 1 year ago.
Java beginner here! As part of practicing programming, I've run into Pascal's triangle. I tried to implement a solution where the triangle is printed like so:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
So roughly right-sided. My solution though runs into multiple errors, and although I would appreciate help with that, I would primarily like to know if I am thinking correctly with my solution. (For some functions I am using a custom library)
public static void main(String[] args) {
int input = readInt("Enter triangle size, n = ");
array = new int[input][input];
for (int i = 0; i < input; i++) { // rows
for (int j = 0; j < i + 1; j++) { // columns
if (i = 0) {
array[i][0] = 1;
} else if (i != 0 && i == j) {
array[i][j] = 1;
} else {
array[i][j] = array[i - 1][j] + array[i - 1][j - 1];
}
}
}
// print out only the lower triangle of the matrix
for (int i = 0; i < input; i++) {
for (int j = 0; j < input; j++) {
if (i <= j) {
System.out.println("%d ", array[i][j]);
}
}
}
}
You were on the right track. Here's how I implemented it:
Scanner sc = new Scanner(System.in);
System.out.print("Enter triangle size, n = ");
int n = sc.nextInt();
sc.close();
//This will be a jagged array
int[][] array = new int[n][0];
for (int i = 0; i < n; i++) {
//Add the next level (it's empty at the start)
array[i] = new int[i + 1];
for (int j = 0; j <= i; j++) {
//At the ends, it's just 1
if (j == 0 || j == i) {
array[i][j] = 1;
} else { //The middle
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
}
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j <= i; j++) {
//printf is what you use to do formatting
System.out.printf("%d ", array[i][j]);
}
//Without this, everything's on the same line
System.out.println();
}
Your else part was correct, but you didn't check if j equaled 0 before that. Instead of setting the current element to 1 when i was 0 or when i equaled j, you should have done it when j was 0 or when i equaled j. Because of this mistake, in later rows where i was not 0, but j was, you tried to access array[i - 1][j - 1], which was basically array[i - 1][-1], causing an IndexOutOfBoundsException.
I also made a jagged array instead of an even matrix because it made more sense that way, but it shouldn't matter much.
Also, this wasn't an error, but you did else if (i!=0 && i==j) The i != 0 part is unnecessary because you checked previously if i == 0.
Link to repl.it
I'm supposed to write a program that reads an array of ints and outputs the number of "triples" in the array.
A "triple" is three consecutive ints in increasing order differing by 1 (i.e. 3,4,5 is a triple, but 5,4,3 and 2,4,6 are not).
How do I check for the "triples"?
Current Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
int iterator = 0;
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
} for(int j =0; j < size; j++){
iterator++;
}
}
}
The following code loops through the entire array of integers. Inside of the loop it is checked if the third integer exists inside of the array ((i + 2) < array.Length) and the other 2 conditions are all about whether value1 is the same as the value2 decreased by 1 (array[i] == array[i + 1] - 1 and array[i + 1] == array[i + 2] - 1):
for (int i = 0; i < array.Length; i++)
{
if((i + 2) < array.Length && array[i] == array[i + 1] - 1 && array[i + 1] == array[i + 2] - 1)
System.out.println("Three values at indexes" + i + " " + (i + 1) + " and " + (i + 2) + " are a triple");
}
The code below is C# and sadly not compatible to Java that easily, I'll just leave that here for anyone who wants to know how its handled in C# (the vt variable is a so called ValueTriple):
(int, int, int) vt;
for (var i = 0; i < array.Length; i++)
{
if (i + 2 >= array.Length) continue;
vt = (array[i], array[i + 1], array[i + 2]);
if (vt.Item1 == vt.Item2 - 1 && vt.Item2 == vt.Item3 - 1)
Console.WriteLine($"Three values at indexes {i}, {i + 1} and {i + 2} (Values: {array[i]}, {array[i + 1]}, {array[i + 2]}) are a triple");
}
You may try following code
import java.util.Scanner;
public class Triplet {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
}
Integer counter = 0;
for(int i = 0; i < size-2; i++) {
if(array[i] == array[i+1] - 1 && array[i] == array[i+2] - 2) { //checking if three consecutive ints in increasing order differing by 1
counter++;
}
}
System.out.println(counter);
}
}
Hope this will help.
A method to find out the number of triplets could look like this. You then just have to call the method depending how your input is obtained and you wish to present the result.
public static int getNumberOfTriplets(int[] toBeChecked) {
int numberOfTriplets = 0;
int nextIndex = 0;
while (nextIndex < toBeChecked.length - 2) {
int first = toBeChecked[nextIndex];
int second = toBeChecked[nextIndex + 1];
int third = toBeChecked[nextIndex + 2];
if ((first + 1 == second) && (second + 1 == third)) {
numberOfTriplets++;
}
nextIndex++;
}
return numberOfTriplets;
}
Regardless of allowing the numbers to be in more than one triplet, the answer is fairly similar in how I would personally approach it:
//determines if the input sequence is consecutive
public boolean isConsecutive(int... values) {
return IntStream.range(1, values.length)
.allMatch(i -> values[i] == values[i - 1] + 1);
}
public int countTriples(int[] input, boolean uniques) {
if (input.length < 3) {
return 0;
}
int back = 0;
for(int i = 2; i < input.length; i++) {
if (isConsecutive(input[i - 2], input[i - 1], input [i]) {
back++;
if (uniques) { //whether to disallow overlapping numbers
i += 2; //triple found, ignore the used numbers if needed
}
}
}
return back;
}
Then in calling it:
Int[] input = new int[] {1, 2, 3, 5, 6, 7, 8};
countTriples(input, true); //3
countTriples(input, false); //2
In this case, I want to add two numbers in this array in to obtain a specific sum when added, let’s say, 4. I also want to output what indices are being added in order to obtain that specific sum, just to see the inner workings of my code. What am I doing wrong?
public static int addingNumbers(int[] a) {
int i1 = 0, i2 = 0;
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
if(a[i] + a[j] == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
System.out.println("The indices are " + i1 + " and " + i2);
return i1;
}
public static void main(String args[]) {
int[] a = {1, 2, 3, 4, 5, 6};
System.out.println(addingNumbers(a));
}
The error you are making is using only one loop that iterates over the array once:
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
In your loop you are setting i to 0 and j to 1, then you increment them with every step. So you are only comparing adjacent places in your array:
iteration: a[0] + a[1]
iteration: a[1] + a[2]
iteration: a[2] + a[3]
etc. pp
Since your array doesn't have two adjacent elements that sum up to 4 your if(a[i] + a[j] == 4) will never be entered and i1, i2 will still be 0 when the loop is finished.
To compare every array element with each other you should use 2 nested loops:
public static int addingNumbers(int[] a) {
int i1 = -1, i2 = -1;
for(int i = 0; i < a.length ; i++) {
for(int j = i+1; j < a.length ; j++) {
if(a[i] + a[j] == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
}
if(i1>=0 && i2 >=0) {
System.out.println("The indices are " + i1 + " and " + i2);
}
return i1;
}
Note that this will only print out the last detected 2 indices that add up to 4. If you want to be able to detect multiple possible solutions and print them out could for example move the System.out.println into the if block.
It can never be == 4 because 1+2=3 then 2+3=5. So it does nothing.
There is a logic error in your code. The sum you are checking in your code is never for.
I added some debug output for easy checking:
public static int addingNumbers(int[] a) {
int i1 = 0, i2 = 0;
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
int sum = a[i] + a[j];
System.out.println(sum);
if(sum == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
System.out.println("The indices are " + i1 + " and " + i2);
return i1;
}
Output is: 3
5
7
9
11
The indices are 0 and 0
0
this algorithm will never be able to add a[0] to a[2], be cause when you put j=i+1 it will always be 0+1 then 1+2 ... The sum of tow adjacent numbers is never pair.
An other matter is the condition to stop your loop must be j < a.length-1
try to explain more of what you want from your algorithm.
Are you over complicating this on purpose?
Trying to figure out your intention for this task.
Why don't you just do (this is pseudo):
for length of i {
if (a[i] + a[i+1] == 4) {
System.out.println("The indices are " + a[i] + " and " + a[i+1]);
}
}
I want to write a program that reads a matrix of positive int with the format txt (the matrix can be of any size). (I read the matrix from the console).
The program looks for a location in the matrix such that if a knight is positioned at that location, all possible moves will land the knight on elements which have the same value and it must have at least 2 options. The program prints the result. for example, the black places are where the knight can move to.
This is the code I wrote. the problem is that i'm getting: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Knights.main(Knights.java:23)", I know it has a problem with the first row (there is no backwards value in the start of the matrix) but I don't know how can I fix it.
public static void main (String[] args) {
String size = StdIn.readLine();
int counter = 0;
int matrixSize = Integer.parseInt(size);
int [][] matrix = new int [matrixSize+1][matrixSize+1];
for (int i=0; i <= matrixSize-1; i++) {
for (int j=0; j <= matrixSize-1; j++) {
if ((matrix[i][j]) > 0)
matrix[i][j] = StdIn.readInt();
}
}
for (int k=0; k <= matrixSize-2; k++) {
for (int l=0; l <= matrixSize-2; l++) {
if (matrix[k-1][l+2] == matrix[k+1][l+2]) {
counter +=1;
StdOut.println(counter); }
else if (matrix[k-1][l+2] == matrix[k+1][l-2]) {
counter +=1;
StdOut.println(counter); }
if (counter>=2)
StdOut.println("location "+ matrix[k][l] + "is surrounded by the number " +matrix[k+1][l-2]);
}
}
if (counter < 2)
StdOut.println("no surrender by any number");
}
}
I would add an extra test here to check if k-1 is greater than 0.
As && is a short-circuit operator, the second expression is not tested if the first is false and can not throw an exception.
Solution
if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l + 2]) {
counter += 1;
StdOut.println(counter);
} else if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l - 2]) {
counter += 1;
StdOut.println(counter);
}