0

I am getting error while running the below code "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0" And I want to know the difference between next() and nextLine() method.

        //Scanner
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++){
            arr[i] = sc.nextInt();
        }
        int q=sc.nextInt();
        String str[] = new String[q];
        for(int i=0;i<q;i++)
        {
            str[i] = sc.nextLine();
        }
        sc.next();
        for(int i=0;i<q;i++){
            System.out.println(str[i]);
            if(str[i].charAt(0) == 'I' ){
               String s1[] = str[i].split("\\s+");`enter code here`
               System.out.println(s1[0]);`enter code here`
            int value = Integer.valueOf(s1[1]);
            arr[value]+= 1;
            }
            if(str[i].charAt(0) == 'U'){
                String aa ="aman 2";
                String s2[]= aa.split("\\s+");
                int pos = Integer.valueOf(s2[1]);  
                int val = Integer.valueOf(s2[2]);
                arr[pos] = val;
            }
            if(str[i].equalsIgnoreCase("left"))
                {
                    int j = 0;
                    int tmp = arr[0];
                    for(j=0;j<n-1;j++){
                        arr[j]=arr[j+1];
                    }
                    arr[j]=tmp;
                }
            if(str[i].equalsIgnoreCase("right")){
                  int k = 0;
                    int temp = arr[0];
                    for(k=0;k<n-1;k++){
                        arr[k]=arr[k+1];
                    }
                    arr[k]=temp;
            }
            if(str[i].equals('?')){
                String s4[] = str[i].split("\\s+");
                int position = Integer.valueOf(s4[1]);
                System.out.println(arr[position]);
            }
        }

1 Answers1

1

I think the problem is the following line:

if(str[i].charAt(0) == 'I' ){

If str is an empty String, you cannot get the first character. You can test ifa String is empty by using .isEmpty().

Scanner#nextLine() reads (as the name says) the next line from an InputStream(in your case System.in).

Scanner#next() can read the next line butit can also read less. It reads until it reaches certain delimitors.

You can configure the delimitors. By default, it splits by delimitors like spaces, line breaks etc.

dan1st
  • 6,537
  • 6
  • 18
  • 44