Search code examples
javaarraysstackcharacter

How can I input a string in a scanner and convert it into character and that character becomes my stack?


I am new to java and I am stuck with my code because I have no idea how my character becomes my stack

Stack<Character> charStack = new Stack<Character>();
        Scanner scan = new Scanner(System.in);
        System.out.print("Input a word: ");
        String str = scan.nextLine();
        char[] char1 = new char [str.length()];

        for (int b = 0; b<char1.length; b++){
            charStack.push(b);
            System.out.println(charStack);
            charStack.pop(); 
}

error: incompatible types: int cannot be converted to Character charStack.push(b);

   and the output should be:
      ['W','O','R','D']
      ['W','O','R']  
      ['W','O'] 
      ['W'] 

Solution

  • There are two issues with your code

    Instead of this char[] char1 = new char [str.length()]; convert your input string to character array like this str.toCharArray()

    Then instead of pushing the index integer to the character stack, push the character charStack.push(charArray[i]);

    public static void main(String[] args) {
       Stack<Character> charStack = new Stack<Character>();
        Scanner scan = new Scanner(System.in);
        System.out.print("Input a word: ");
        String str = scan.nextLine();
        char[] charArray = str.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            charStack.push(charArray[i]);
        }
        while (!charStack.empty()) {
            System.out.println(charStack);
            charStack.pop();
        }
    }