1

I am learning java and I have written a program on stack(LIFO). Aim of the code is to read integers from keyboard and build a stack.

class StackDemo
{
    public static void main(String[] arg)
    throws java.io.IOException{
        Stack s1 = new Stack();

        char ch1;
        System.out.println("would you like to push data into stack??? Enter y for yes. Enter n for no");
        ch1 = (char) System.in.read();

        if(ch1 == 'y')
        {
            for(int i=0; i<10; i++)
            {
                int input;
                System.out.println("Enter an integer to push to the stack");
                input = (int)System.in.read();

                s1.push(input);
            }
        }
        else if(ch1 == 'n')
        {
        }
        else
        {
            System.out.println("push - Enter a valid input");
        }
     }
}

When I run the program, following result is displayed on console.

----------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
----------------------------------------------------------------------------

But Expected result is

-------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
-------------------------------------------------------------------------

Can anyone help what is the problem in code?

Thanks in advance, Nikhil S

4
  • 1
    use an instance of Scanner, instead of System.in Commented May 21, 2015 at 11:19
  • 1
    Did you try running that in a debugger? I also fail to see where Value is pushed onto stack successfully is printed so is there something missing? Commented May 21, 2015 at 11:20
  • Basically, you order to read System.in without testing if it is ready (if someone entered a character). Commented May 21, 2015 at 11:24
  • Did you try to print what input variable is reading? Commented May 21, 2015 at 11:27

5 Answers 5

2

You are facing this problem because you use System.in input stream directly to read your input. It does not work the way you intend it to. You get multiple inputs because System.in treats new line [Enter] you enter after pressing 'y' also as input. One way to use System.in would be to wrap it in Scanner as suggested below:

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

class StackDemo {

    public static void main(String[] arg) throws java.io.IOException {
        Scanner in = new Scanner(System.in);
        Stack s1 = new Stack();
        System.out.println("Would you like to push data into stack??? Enter y for yes. Enter n for no");
        String ch1 = in.nextLine();
        if (ch1.equalsIgnoreCase("y")) {
            for (int i = 0; i < 10; i++) {
                System.out.println("Enter an integer to push to the stack");
                int input = (int) in.nextInt();
                s1.push(input);
            }
        } else if (ch1.equalsIgnoreCase("n")) {
        } else {
            System.out.println("Push - Enter a valid input");
        }
    }
}

Alternately, you may use BufferedReader instead of Scanner. You should read up more on this from the docs. You can find the description here and here. Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

As in: System.in.read() does not read

You need to use the Scanner class. You can instantiate a scanner object like so

Scanner scan = new Scanner(System.in);

then use

input = scan.nextInt();

Comments

1

The problem is that when you type 'y' and press Enter, you actually enter 3 chars: y, \r, \n (13 cartridge return and 10 line feed). The problem can be avoid with one of the above approaches. I would use the one #Fazovsky has written as it is simpler.

Comments

0

I'd suggest you to define a reader object.In your code, there might be an error because of two in a row "read.in" operations without closing that readers. Here is the sample:

public class Test {
    public static void main(String[] args) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try{
            int i = Integer.parseInt(br.readLine());
        }catch(NumberFormatException nfe){
            System.err.println("Invalid Format!");
        }
        br.close();
    }
}

Comments

0

Use Scanner for int value.

class StackDemo {
    public static void main(String[] arg) throws java.io.IOException {
        Stack s1 = new Stack();
        char ch1;
        System.out
                .println("would you like to push data into stack??? Enter y for yes. Enter n for no");
        ch1 = (char) System.in.read();
        Scanner scan = new Scanner(System.in);
        if (ch1 == 'y') {
            for (int i = 0; i < 10; i++) {
                int input;
                System.out.println("Enter an integer to push to the stack");
                input = scan.nextInt();
                s1.push(input);
            }
        } else if (ch1 == 'n') {
        } else {
            System.out.println("push - Enter a valid input");
        }
        System.out.println("Stack Values: " + s1);
    }
}

1 Comment

Thanks Everyone. I need to study some more chapters to start using Scanner. But I got the reason why my code is failing. Thanks for your valuable comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.