0

I'm trying to make a simple program that uses a scanner for input and has a while loop that continues taking input until an end character is entered. I want the scanner to take input and add a string to the stack list. I'm trying to figure out why this code doesn't terminate the while loop when a space is typed.

import java.util.Scanner;

public class ReverseString<E> {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Stack<String> stack = new Stack();

    //while(scan.hasNext() && !stack.equals(" ")){
 //       while(!scan.nextLine().equals("")){
    while (scan.hasNext()) {
        stack.push(scan.next());
        if (scan.equals(" ")) {
            break;
        }

    }

    System.out.print(stack.pop() + " ");


 }
}
Michael Fogarty
  • 295
  • 1
  • 3
  • 10

3 Answers3

0
while (scan.hasNext()) {
    stack.push(scan.next());
    if (scan.equals(" ")) {
        break;
    }

}

change to

while (scan.hasNextLine()) {
    String value = scan.nextLine();
    if (" ".equals(value)) {
        break;
    }
    stack.push(value);
}

scan is a Scanner, it's not a String, scan.equals(" ") would always return false.

Bejond
  • 1,085
  • 9
  • 18
0

You should use nextLine instead

while (scan.hasNextLine()) {
    String nextInput = scan.nextLine();
    stack.push(nextInput );
    if (nextInput.equals(" ")) {
        break;
    }
}
Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
-1

You're doing,

if (scan.equals(" ")) {
    break;
}

which means you're comparing the Scanner object scan to a space. Try doing the following instead(you have to compare the scan.next() with a space):

import java.util.Scanner;

public class ReverseString<E> {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Stack<String> stack = new Stack();

    //while(scan.hasNext() && !stack.equals(" ")){
 //       while(!scan.nextLine().equals("")){
    while (scan.hasNext()) {
        String nextInput = scan.next();
        stack.push(nextInput );
        if (nextInput.equals(" ")) {
            break;
        }

    }

    System.out.print(stack.pop() + " ");


 }
}
mettleap
  • 1,324
  • 6
  • 16