array index out of bounds in java -
i trying make program wherein user prompt on how many inputs input. have 3 user inputs in multi array, if user input 1 1 user input appear. otherwise, if user inputs 2 or 3, 2 or 3 user inputs appear. upon testing program, ran, java.lang.arrayindexoutofboundsexception error appeared. can't seem find error in here, i've tried adding index on multi array still same error.
import java.io.*; public class student { private int stud_id; private string stud_prog; object ctr1; bufferedreader in = new bufferedreader(new inputstreamreader(system.in)); object stud [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}}; public void stud() throws numberformatexception,ioexception{ system.out.print("enter how many inputs: "); int num1 = integer.parseint(in.readline()); (int x = 1; x<=num1;x++){ (int = 0 ; i<num1;){ system.out.println(stud[x][i]); ctr1 =in.readline(); i++; } } } }
///////////////////////////////////////////////////////////////////main/////////////////////////////////////////////////////////////////////////////////
import java.io.ioexception; public class persontest { public static void main(string[]args) throws numberformatexception,ioexception{ student s = new student(); s.stud(); } }
array index starts 0 , end length-1
change:
for (int x = 1; x<=num1;x++){
to:
for (int x = 0; x<num1;x++){
first check length of array before iterating
if(num1<=stud.length){ (int x = 0; x<num1;x++){ .... } }
note: multidimensional array can contains variable no of columns. should use stud[row].length
no of columns of row.
stud.length
gives no of rowsstud[i].length
gives no of columns of ith row
as per comment
what mean if user inputs 1 1 user attribute appear, if 2 2 , on...
is looking for?
string stud[] = { "enter name:", "enter age:", "enter gender:" }; system.out.print("enter how many inputs: "); int num1 = integer.parseint(in.readline()); if (num1 <= stud.length) { (int x = 0; x < num1; x++) { system.out.println(stud[x]); //read input user } }
Comments
Post a Comment