This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am new to programming and while running some new code in eclipse, I came across this error and am completely lost.
import java.util.Scanner;
public class Lab6
{
public static void main(String[] args)
{
// Fill in the body according to the following comments
Scanner in= new Scanner(System.in);
// Input file name
String FileName=getFileName(in);
// Input number of students
int numOfStudents = FileIOHelper.getNumberOfStudents(FileName);
Student students[] = getStudents(numOfStudents);
// Input all student records and create Student array and
// integer array for total scores
int[]totalScores = new int[students.length];
for(int i=0; i< students.length; i++)
{
for(int j=1; j<4; j++)
{
totalScores[i]= totalScores[i]+students[i].getScore(j);
}
}
// Compute total scores and find students with lowest and
// highest total score
int i;
int maxIndex =0;
int minIndex =0;
for(i=0; i<students.length; i++);
{
if(totalScores[i]>=totalScores[maxIndex])
{
maxIndex=i;
}
else if(totalScores[i]<=totalScores[minIndex])
{
minIndex=i;
}
}
problem seems to be in the line if(totalScores[i]>=totalScores[maxIndex])
You have a ; after your last for, so after the for executes with no additional commands in each step, the variable i will have the value students.length which is outside the bounds of the array. Then the { ... } block following the for is executed once with that final value of i, causing the exception.
Remove that ; and it should work.
problem in this lines
int[]totalScores = new int[students.length];
for(int i=0; i< students.length; i++)
{
for(int j=1; j<4; j++)
{
totalScores[i]= totalScores[i]+students[i].getScore(j);
}
}
you allocated students.length size for the totalscore.. but u are using 4*students.length.. so arrayindex out of bounds occured. use this
int[]totalScores = new int[4*students.length];
thanks
arefin
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
i am very new to programming. I am implementing FirstComeFirstServe(FCFS) Scheduling. I am getting array index out of bound exception while entering first input in ArrivalTime array. It can be a silly mistake, but I cannot figure it out,
Please help me, Thank You for your time.
import java.util.Scanner;
public class FCFS_Practice {
public static Scanner scanner = new Scanner(System.in);
static int numberOfProcess;
int[]ProcessID = new int[numberOfProcess];
int[]ArrivalTime = new int[numberOfProcess];
int[]BurstTime = new int[numberOfProcess];
int[]CompletionTime = new int[numberOfProcess];
int[]TurnAroundTime = new int[numberOfProcess];
int[]WaitingTime = new int[numberOfProcess];
float avgWaitingTime,avgTurnAroundTime;
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
}
public void inputArrivalAndBurstTime(){
for(int i = 0;i < numberOfProcess;i++){
System.out.printf("Enter Arrival Time for Process %d: ",i+1);
ArrivalTime[i] = scanner.nextInt();
scanner.nextLine(); // Buffer Flush
System.out.printf("Enter Burst Time for Process %d: ",i+1);
BurstTime[i] = scanner.nextInt();
scanner.nextLine(); // buffer flush
ProcessID[i] = i+1;
}
}
public void calculateCompletionTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
if(i==0){
CompletionTime[0]=BurstTime[0];
} else if (ArrivalTime[i]<CompletionTime[i-1]) {
CompletionTime[i]=CompletionTime[i-1]+BurstTime[i];
} else {
CompletionTime[i]=ArrivalTime[i]+BurstTime[i];
}
}
}
public void calculateTurnAroundAndWaitingTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
TurnAroundTime[i]=CompletionTime[i]+ArrivalTime[i];
WaitingTime[i]=TurnAroundTime[i]-BurstTime[i];
}
}
public void getAvgWaitingTimeAndAvgTurnAroundTime(){
for(int i = 0 ; i<numberOfProcess;i++){
avgTurnAroundTime+=TurnAroundTime[i];
avgWaitingTime+=WaitingTime[i];
}
avgWaitingTime = avgWaitingTime/numberOfProcess;
avgTurnAroundTime = avgTurnAroundTime/numberOfProcess;
}
public void getTable(){
System.out.println("ProcessNo. ArrivalTime BurstTime CompletionTime TurnAroundTime WaitingTime");
for(int i = 0 ; i < numberOfProcess ; i++){
System.out.println(ProcessID[i]+"\t\t"+ArrivalTime[i]+"\t\t"+BurstTime[i]+"\t\t"+CompletionTime[i]+"\t\t\t"+TurnAroundTime[i]+"\t\t\t"+WaitingTime[i]);
}
scanner.close();
}
}
OutPut
The problem with your code is that you initialize arrays of int (ProcessID..) with the static int numberOfProcess - which initialized by default as 0.
You update it from Scanner at takeInput method but length of the arrays have been already initialized as 0 length.
You have to work with the initialization process to set initial arrays values only after you get your numberOfProcesses variable value from Scanner. You can read more about default initialization at Java Official Documentation.
As fast workaround for learning purpose just change default value. But remember that error returns if numberOfProcess will be higher, so to modify code is mandatory for solid code practice and passing of automation tests.
static int numberOfProcess = 10;
As more solid (but not a very nice one solution) initialize your arrays only after you know the correct value of numberOfProcess variable:
int numberOfProcess;
int[]ProcessID;
int[]ArrivalTime;
int[]BurstTime;
int[]CompletionTime;
int[]TurnAroundTime;
int[]WaitingTime;
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
ProcessID = new int[numberOfProcess];
ArrivalTime = new int[numberOfProcess];
BurstTime = new int[numberOfProcess];
CompletionTime = new int[numberOfProcess];
TurnAroundTime = new int[numberOfProcess];
WaitingTime = new int[numberOfProcess];
}
If you use ArrayList instead of []int you don't need to set array length. However, you have also to learn deep the difference between ArrayList (resizable array) and array - there are tasks where array is preferable.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
there is an issue in data.txt we have 4 rows and 3 cols and gives me error out of bound kindly someone solve this but when I pass 4x4 in rows and cols it works well but it didnt meet project requirement
public class ReadMagicSquare {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
Scanner sc = new Scanner(new BufferedReader(new FileReader("data.txt")));
int rows = 4;
int columns = 3;
int [][] myArray = new int[rows][columns];
while(sc.hasNextLine()) {
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<line.length; j++) {
myArray[i][j] = Integer.parseInt(line[j]);
}
}
}
for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}
}
}
in data.txt file
2 -1 1
6 4 24
2 19 7
for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}
myArray.length gives you the number of rows in the 2D array, so in the inner loop, j would go from 0 to less than 4 instead of 0 to less than 3, which would give you an out of bound error.
You need to iterate j from 0 to the number of columns.
Here is the code where it calculates the dimensions of the matrix in the file, read it from the file and construct the matrix and prints it.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (new File("data.txt"));
Scanner inFile = new Scanner (new File("data.txt"));
/*To get the dimension of the matrix*/
String[] line = sc.nextLine().trim().split("\\s+");
int row = 1, column = 0;
column=line.length;
while (sc.hasNextLine()) {
row++;
sc.nextLine();
}
sc.close();
/*To read the matrix*/
int[][] matrix = new int[row][column];
for(int r=0;r<row;r++) {
for(int c=0;c<column;c++) {
if(inFile.hasNextInt()) {
matrix[r][c]=inFile.nextInt();
}
}
}
inFile.close();
/*To print the matrix*/
System.out.println(Arrays.deepToString(matrix));
}
I am trying to copy my instrumentalist array into a new array called copy array and when I go to run it, it just goes blank after I am done the do while loop and doesn't print out the musicians names I have entered. from what I can find and know already I thought this is the right way to copy an array to another. thank you in advanced for your personal input
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
final int MAXPEOPLE=100;
instrumentalist [] instrumentalistArr;
instrumentalistArr=new instrumentalist[MAXPEOPLE];
char choice;
int index=0;
int instrumentalistCOUNT=0;
do {
instrumentalist ainstrumentalist = new instrumentalist();
ainstrumentalist.readin();
instrumentalistArr[index]=ainstrumentalist;
instrumentalistCOUNT++;
index++;
System.out.println("would you like to enter another data set yes or no");
choice=keyboard.next().charAt(0);
} while(choice!='n');
instrumentalist [] copyarray;
copyarray=new instrumentalist[instrumentalistArr.length];
for(int i=0; i<instrumentalistCOUNT; i++) {
copyarray[i]=instrumentalistArr[i];
}
for(int i=0; index<instrumentalistCOUNT; i++) {
System.out.println("musician"+" "+ copyarray[index].getmusicianname());
}
}
}
In this for loop:
for(int i=0; index<instrumentalistCOUNT; i++)
{
System.out.println("musician"+" "+ copyarray[index].getmusicianname());
}
Change index to i.
So your for loop should be:
for(int i=0; i<instrumentalistCOUNT; i++)
{
System.out.println("musician"+" "+ copyarray[i].getmusicianname());
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Currently having difficulty with Selection Sort and Bubble Sort codes.
The selection sort is used to sort out student ID in ascending order and the bubble sort is used to sort out last names in ascending order. The program compiles but crashes upon choosing choice 10 or 11.
My array is declared as follows:
student[] list = new student[100]; //my array
This is the code that I have for selection sort and bubble sort. I am using an array with methods:
if (choice == 10) { // Dissplay the sorted array by student id
SortArrayBySelection(list);
System.out.println("Sorted studentid are:");
for (int i =0; i< studentNumber; i++)
{
System.out.println(list[i]);
}
}
if (choice == 11){ // Display the sorted array by family name
BubbleSort(list);
System.out.println("The sorted names are:");
for(int i = 0; i < studentNumber; i++)
{
System.out.println(list[i].Getfamilyname());
}
}
} while (choice != 1);
}
public static void SortArrayBySelection(student[] arrayToSort){ // Function to sort out the array on sutdentid
for(int i = 0; i < arrayToSort.length-1; ++i)
{
int minIndex = i;
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
for(int j = i + 1; j <arrayToSort.length; ++j)
{
int studentid1 = arrayToSort[j].Getstudentid();
if(studentid1 < studentid2)
{
minIndex = j;
}
}
int temp = studentid3;
studentid3 = studentid2;
studentid2 = temp;
}
}
public static void BubbleSort(student[] arraySort){
String t;
for(int i = 0; i<arraySort.length; i++){
for(int j=0; j<arraySort.length-1;j++){
String str1 = arraySort[j].Getfamilyname();
String str2 = arraySort[j+1].Getfamilyname();
if(str1.compareTo(str2)<0){
t = str1;
str1 = str2;
str2 = t;
}
}
}
}
Any suggestions would be appreciated! thank you
Errors:
Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)
Exception in thread "main" java.lang.NullPointerException
at client.Client.BubbleSort(Client.java:288)
at client.Client.main(Client.java:246)
As you have not mentioned line numbers in your code, also the Student class and the code where you are preparing the student[] list = new student[100]. So, as far as i can see the code from following lines you can get the java.lang.NullPointerException
Your list length will be always 100 as you are creating it with that value. So if it something dynamic values which you are preparing at runtime then it will be better if you use ArrayList<student> list=new ArrayList<student>(); and add the values using list.add(yourObject);.
Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)
For this error you are calling SortArrayBySelection method and the lines which may end up in the above errors are
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
int studentid1 = arrayToSort[j].Getstudentid();
Reason for the error :
You don't have the values present at the given index and as you are creating an array of length 100 where you put only let say 10-15 values then it will always have no values in other location. But your for-loop will go to 100 index position in which after 10-15 index you will always get null by calling the getters.
Same reason is for your other method as well.
Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}