Reading ints into a multidimensional array - java

My problem occurs during the for loops to read in the values from the file into my scores array. The program reads in and prints the first 6 values or 2 lines of ints, but then I get ArrayIndexOutOfBoundsException: 2
I have no idea why this is stopping there. If I have j<1000, it will read 17 values. Anyway, the file I'm reading in is below (wasn't sure the formatting for a text file).
Any help would be appreciated
Andy Matt Tom
3 2 3
4 4 5
3 3 2
2 2 2
2 4 2
2 3 2
4 4 5
2 3 3
4 3 5
3 3 6
2 2 5
3 3 3
3 3 2
3 2 4
3 2 6
3 4 3
2 3 2
2 2 2
50 52 62
public static void main( String args[] )
{
try
{
if (args.length<1)
{
System.out.printf("\n...You must enter the name of a file\n");
System.exit(0);
}
Scanner infile = new Scanner ( new File(args[0]) );
int par= 3;
int play= 18;
String[] players= new String[play];
int k=0;
int scores[][]= new int[play-1][par-1];
while(infile.hasNext())
{
players[k]=infile.next();
k++;
if (k==play)
break;
}
for(int j=0; j<par; j++)
{
for (int i=0; i<play; i++)
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Bug");
System.exit(0);
}
}

int scores[][] = new int [play-1][par-1];
Why -1? That's where your AIOOB is coming from.

There are two issues:
int scores[][] = new int[play-1][par-1]; // Why -1 ?
and:
for(int j=0; j<par; j++) // should be 'j < play' as 'j'
// is index to dimension
// with size 'play'
{
for (int i=0; i<play; i++) // should be 'i < par' as 'i' is
// index to dimension with
// size 'par'
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}

Actually, there are three issues.
There are only 3 players, not 18
You need a 18x3 array, not a 17x2 array
[i][j] instead of [j][i]
Diff of your code against my modified version (which works like a charm):
22c22
< String[] players= new String[play];
---
> String[] players= new String[par];
24c24
< int scores[][]= new int[play-1][par-1];
---
> int scores[][]= new int[play][par];
32c32
< if (k==play)
---
> if (k==par)
41,42c41,42
< scores[j][i]=infile.nextInt();
< System.out.println(scores[j][i]);
---
> scores[i][j]=infile.nextInt();
> System.out.println(scores[i][j]);

Related

Index n out of bounds for length n Exception. I am trying to try to remove duplicates from an array to make a new array then display it [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
Expected output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Here are the distinct numbers 1 2 3 4 5
output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 5
at Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index++;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i++) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i + 1]) {
numArray[uniqueIndex++] = numArray[i];
}
}
numArray[uniqueIndex++] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " + numArray[uniqueIndex]);
return uniqueIndex;
}
}
The exception message indicates that you are trying to access an index that does not exist:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at Main.main(Main.java:26)
Illegal access occurs on this line:
numArray[index] = num;
The reason is that in numArray there is no index with the value of the index variable.
PS: note that on line 19 you assign the length of args to the variable index.
The problem is that you define these values:
index = args.length;
numArray = new int[index];
and then in the first loop iteration you access
numArray[index] = num;
which is not a valid index since it is too big by 1.
The real problem here is that you are using index as a running variable in your loop, but it is not set to the starting value of 0. You are using the same variable for two different purposes.
Either
set index = 0; before the loop or
use a different variable in your loop, such as i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i++] = num;
}

Last line of textfile not storing correctly into 2D array

My scanner is not accessing last line of my text file correctly, thus is storing the last line of the text file as all 0's into my 2D array instead of what is actually there. I believe I have provided everything that would give context as to what is going wrong, but if more info is needed I can update this question, thanks in advance.
//Creates 2-d array object, stores values from file.
public DominoSort (String fileName) throws java.io.FileNotFoundException{
this.grid = new int [7][8]; //2-d array to hold values from text file
Scanner br = new Scanner(new File(fileName));
String line = br.nextLine();
int r = 0;
int c = 0;
while (br.hasNextLine) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
//this.setS = new ArrayList<>();
//this.pairMappings = new ArrayList<ArrayList<dominoLocation>>();
br.close();
}
//Print grid function, prints out the grid
public void printGrid() {
for(int r = 0; r < this.grid.length; r++) {
System.out.println("");
for(int c = 0; c < this.grid[r].length; c++) {
System.out.print(this.grid[r][c] + " ");
}
}
System.out.println("");
}
//Driver for checking
public static void main(String[] args) throws IOException {
// String line;
//System.out.println(new File(".").getAbsolutePath());
Scanner input = new Scanner(System.in); //get textfile name from user input
System.out.print("Enter the file name: ");
String fileName = input.next();
DominoSort dom = new DominoSort(fileName); //this call populates the 2-d array object
//dom.solvePuzzle(6);
dom.printGrid(); //prints 2d array for output
//dom.solvePuzzle(6);
}
text file used for testing / expected output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
2 0 3 2 5 0 5 4 {Notice this line}
actual output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
0 0 0 0 0 0 0 0 {this line is not right}
Your problem lies within the nested while/for loop. It reaches the end condition before all the lines are read. (The nextLine() method doesn't have any more lines before you read the last line). You can see this by putting an extra 1 or 2 lines in your file at the very end, making it show the last lines.
There are a few ways to fix it, one of them is by just adding on an extra for loop after the while loop to compute the last line individually:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
or alternatively, don't increment the line on the first run:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
if (r != 0)
line = br.nextLine();
r++;
c = 0;
}

Input matrices from a file

I'm trying to read 2D matrices from an input file.The​ ​input​ ​file​ ​contains​ ​a​ ​series​ ​of​ ​inputs.​ ​First​ ​line​ ​contains​ ​the matrix ​size​ ​​n.​Next​ ​​n line​ ​contains​ ​​n ​integer​ ​each,​ ​i.e.,​ ​an​ ​n*n matrix.​​The​ ​file​ ​ends with​ ​a​ ​zero​ ​as​ ​matrix ​size.A small sample is below.
2
1 1
1 1
3
3 1 2
1 1 2
2 2 1
6
1 2 3 4 2 3
3 3 4 5 2 1
4 3 3 1 2 3
5 4 3 6 2 1
3 2 4 3 4 3
2 3 4 1 5 6
0
I wrote the following code but it doesn't show what i need.
import java.util.*;
import java.io.*;
public class trial{
public static void main(String[] args) {
try{
//System.out.println(new File("input.txt").getAbsolutePath());
Scanner input = new Scanner(new File("./input.txt"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext()) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf(" %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
}
input.close();
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
The code output is below.It always generates a 2*2 matrix.
1 1
1 1
Array done
3 3
1 2
Array done
1 1
2 2
Array done
2 1
6 1
Array done
2 3
4 2
Array done
3 3
3 4
Array done
5 2
1 4
Array done
3 3
1 2
Array done
3 5
4 3
Array done
6 2
1 3
Array done
2 4
3 4
Array done
3 2
3 4
Array done
1 5
6 0
Array done
First of all, it looks like you want to stop if the user inputs a size of 0, but you don't actually do that, instead you just loop forever. Second, after reading the first matrix, you close the scanner, which isn't what you should do. input.close() should be outside the while loop. Try this.
try {
Scanner input = new Scanner(new File("./input.txt"));
int n;
while (input.hasNextInt() && (n = input.nextInt()) > 0) {
int[][] grid = new int[n][n];
for (int row = 0; row < n; row++) {
for (int column = 0;
column < n && input.hasNextInt(); column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
In your code you are not check when the nextInt is a size and when is a number in matrix . Another thing is that a 0 in size it is for you an EOF , so you shoul get out .
Below a working example :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
try{
Scanner input = new Scanner(new File("pathtofile"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
int cont =0;
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext() && cont != n) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
cont++;
}
System.out.println("Array done");
}
}
else{
input.close();
break;
}
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}}
Result :

Insertion Sort pt2 -Hackerrank

can someone please check my code as to why the last index is not working as intended? Any advice on how to improve this is much appreciated.
import java.io.*;
import java.util.*;
public class Solution {
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 0 ; i < ar.length-1; i++){
key = ar[i];
seen = i;
while (seen <ar.length-1 && ar[seen+1]<key){
ar[seen]= ar[seen+1];
seen = seen+1;
}
ar[seen]=key;
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("");
}
}
Input (stdin) 6 1 4 3 5 6 2
Your Output (stdout) 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 2 6
Expected Output 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6 Compiler Message Wrong Answer
You are doing it in wrong way. Read the part 1 again.
Assume that first element is sorted. Then try to insert element one by one in sorted list.
Try this:
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 1 ; i < ar.length; i++){
key = ar[i];
seen = i;
while (seen > 0 && ar[seen-1] > key) {
ar[seen] = ar[seen-1];
seen = seen - 1;
}
ar[seen]=key;
printArray(ar);
}
}

Bubble Sort Java different outputs

I have been confronting with a very confusing situation, I wrote this BubbleSort program and it ran just fine. with the correct output:
public class BubbleSortInput {
private static void Sorting(int[] intArray)
{
int i, temp=0;
int n = intArray.length;
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = {1,5,65,34,76,234};
Sorting(array);
for(int k = 0; k < array.length; k++)
{
System.out.println(array[k]);
}
}
}
However, I tried to write basically the same code, in the main method, in another class:
class BubbleSort {
public static void main(String[] args) {
int numbers[] = {12,43,65,12,65,92,32,54};
int i,temp=0;
for(i=0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-i-1; j++)
{
if(numbers[i]>numbers[i+1])
{
temp = numbers[i+1];
numbers[i] = numbers[i+1];
numbers[i]= temp;
}
}
}
for(i=0;i<numbers.length;i++)
{
System.out.println(numbers[i]);
}
}
}
The output I get on the second file is completely wrong, even though I used almost the same code, Can someone explain this please?
Output:
12
43
12
12
65
32
32
54
As others pointed out, you should take a look at the bubble sorting algorithm. And just a reminder, run many test cases before stating that your original piece of code works fine. Just to be clear, the first program also gives a wrong output. The output you may have gotten for your input set may be true, but that was a bit sorted to begin with. Try the input set you used in the second program for your first code and identify the errors.And also, take a look at the swapping code inside your for loops.
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
You are assigning the value at [i+1] position to temp. And you are again assigning the value at [i+1] to the location i. So the value at the location [i] was lost in the process. Now value at location [i] and [i+1] are same. So work on that as well.
That aside. In Bubble sort, sorting works by swapping adjacent elements. So by the end of the first pass(ascending order sorting), the largest element in the array will be at the end. This process goes on until, all the elements are sorted.
Example:
First Pass:
( 6 1 3 2 9 ) –> ( 1 6 3 2 9 ), Here, algorithm compares the first two elements, and swaps since 6 > 1.
( 1 6 3 2 9 ) –> ( 1 3 6 2 9 ), Swap since 6 > 3
( 1 3 6 2 9 ) –> ( 1 3 2 6 9 ), Swap since 6 > 2
( 1 3 2 6 9 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (9 > 6), algorithm does not swap them.
Second Pass:
( 1 3 2 6 9 ) –> ( 1 3 2 6 9 )
( 1 3 2 6 9 ) –> ( 1 3 4 6 9 ), Swap since 3 > 2
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9) –> (1 2 3 5 9 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 3 5 9 ) –> (1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
I don't think your bubble sorting code is correct. Here is your loop:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
Note that you never use the variable j. So all it does is loop through the array and then swap the two elements if the first one is larger than the second one. You should take a look at the Bubble sort algorithm again and re-write your code.
The sorting logic you are using is incorrect.
Bubble sort compares each pair of adjacent items and swaps them if they are in the wrong order (not in ascending order).
By the end of the first pass(ascending order sorting), the largest element in the array will be at the last index.
By the end of the second pass(ascending order sorting), the second largest element in the array will be at the second last index and so on.....
Visit http://visualgo.net/sorting for better understanding.
So, in your code you should compare the items with the 2nd initialization (variable j in your case). After modification it should look like:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < (n-i)-1; j++)
{
if(intArray[j]>intArray[j+1])
{
temp = intArray[j];
intArray[j] = intArray[j+1];
intArray[j+1] = temp;
}
}
}

Categories

Resources