Home > OS >  reverse a string by using stack in java geting exception error
reverse a string by using stack in java geting exception error

Time:03-09

I am new here and try to create this code but when i run my code i get exception error, can you tell me how can i correct my mistake which line code is not proper.

import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;

public class Stack_and_stuff {

    static Stack<Character> stk = new Stack<Character>();
    public static void pushelmnt(Stack stk, char c){
        // Insert character in the stack method
        stk.push(c);
    }
    public static void popelmnt(Stack stk){
        try{
            // Take element back into the stack
            System.out.print(stk.pop());
        }
        // If stack is empty then thought the Exception handler code :
        catch (EmptyStackException e){

        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Insert a string in the below :-");
        String line = in.nextLine();
        // making character string
        for(int i=0;i<=line.length();i  ){
            pushelmnt(stk,line.charAt(i));
        }
        for (int j=0; j<=line.length();j  ){
            popelmnt(stk);
        }
    }
}```

CodePudding user response:

In your for statement you iterate untill i<=line.length(), so if the string has a size of 3 (for example the string 'foo') you have an iteration with i=3 and your line.charAt(3) causes IndexOutOfBound because the index starts from 0 and ends at lenght -1 (2 in this case).

CodePudding user response:

You will get the String index out of range exception which is thrown if you try to substring or find a character in a java string. A subset of the sequence of characters can be extracted from a string by using the Java substring() method. The substring index should be any value between 0 and the length of a string.

Simply resolve it by

        for(int i=0;i<=line.length()-1;i  ){
            pushelmnt(stk,line.charAt(i));
        }
  • Related