0

New drivers licence question from code coach

Can i please know why am i getting an array out of bound exception here : import java.util.*; public class Program { public static void main(String[] args) { Scanner ip = new Scanner(System.in); String n=ip.nextLine(); int a=ip.nextInt(); String on=ip.nextLine(); String [] ons=new String[5]; ons=on.split(" "); ons[4]=n; for(int i=0;i<5;i++) { for(int j=i+1;j<5;j++) { String temp; if(ons[i].compareTo(ons[j])>0) { temp=ons[i]; ons[i]=ons[j]; ons[j]=temp; } } } for(int i=0;i<5;i++) { if(ons[i].equals(n)) System.out.print(((i+1)*20)/a); } } }

8th Aug 2024, 5:37 PM
ɪʀꜰᴀɴ I𝚁
ɪʀꜰᴀɴ I𝚁 - avatar
2 Respuestas
+ 2
You are overwriting String[] ons with split. If i enter two words, then that means the array size is going to 2 which causes error on line 11. It because you want to overwrite the fifth element, but array has only two.
9th Aug 2024, 7:18 AM
Ruly
Ruly - avatar
+ 1
ip.nextInt() reads integer but not delimiter after, so do one ip.nextLine() after to read the delimiter int a = ip.nextInt(); ip.nextLine(); then you are trying add name at the end of array ons. if input has 4 names, array after split has length=4 with last index 3 and index 4 does not exist you can and name at the end of input string (with delimiter) before spliting
11th Aug 2024, 7:09 AM
zemiak