0

This code is meant to receive a String input such as "PUSH 5" and take the 5 from the string turn it into an int and do the push command. However I keep getting the string index out of range error on the line "char s = ar[i].charAt(1);" Any ideas?

import java.util.*;

public class lab6
{
    public static void main(String []args)
    {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        
        lab6stack theStack = new lab6stack(size);
        String [] ar = new String [size];
        
        for(int i = 0; i < size; i++)
        {
            ar[i] = sc.nextLine();
            char s = ar[i].charAt(1);
            
            if(s == 'U')
            {
                int num = Integer.parseInt(ar[i].substring(5));
                
                theStack.push(num); 
            }
            
            else if(s == 'O')
            {
                theStack.pop();
            }
        }
        
        while (!theStack.isEmpty())
        {
            System.out.println(theStack.pop());
        }
    }
}
  • Your string is less than 2 characters long. – Andy Turner Nov 18 '20 at 21:28
  • the string im entering is "PUSH 5" – Danial Farhan Nov 18 '20 at 21:30
  • This was already answered [in your other question](https://stackoverflow.com/questions/64900313/keep-getting-the-error-for-input-string-in-my-code). In addition to that, also note that you are just checking for one character. The user could input anything with U or O as the second character and your code would do the same, even if the user didn't input "PUSH" or "POP". Also, your code fails if input is entered in lower case. – JustAnotherDeveloper Nov 18 '20 at 21:30
  • You read an int from the scanner first, then you read a line. The line you've read from it is empty, for reasons described in the dupe. – Andy Turner Nov 18 '20 at 22:23

0 Answers0