结束 while 循环条件

我正在尝试制作一个简单的程序,它使用扫描仪进行输入,并有一个 while 循环,该循环继续输入直到输入结束字符。我希望扫描仪接受输入并将一个字符串添加到堆栈列表中。我试图弄清楚为什么在输入空格时这段代码不会终止 while 循环。


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() + " ");



 }

}


守着星空守着你
浏览 351回答 3
3回答

月关宝盒

你应该nextLine改用while (scan.hasNextLine()) {&nbsp; &nbsp; String nextInput = scan.nextLine();&nbsp; &nbsp; stack.push(nextInput );&nbsp; &nbsp; if (nextInput.equals(" ")) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}

慕沐林林

while (scan.hasNext()) {&nbsp; &nbsp; stack.push(scan.next());&nbsp; &nbsp; if (scan.equals(" ")) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}改成while (scan.hasNextLine()) {&nbsp; &nbsp; String value = scan.nextLine();&nbsp; &nbsp; if (" ".equals(value)) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; stack.push(value);}scan 是一个扫描器,它不是一个字符串,scan.equals(" ")总是返回 false。

Smart猫小萌

你在做,if (scan.equals(" ")) {&nbsp; &nbsp; break;}这意味着您将 Scanner 对象scan与空间进行比较。尝试执行以下操作(您必须将 scan.next() 与空格进行比较):import java.util.Scanner;public class ReverseString<E> {public static void main(String[] args) {&nbsp; &nbsp; Scanner scan = new Scanner(System.in);&nbsp; &nbsp; Stack<String> stack = new Stack();&nbsp; &nbsp; //while(scan.hasNext() && !stack.equals(" ")){&nbsp;//&nbsp; &nbsp; &nbsp; &nbsp;while(!scan.nextLine().equals("")){&nbsp; &nbsp; while (scan.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; String nextInput = scan.next();&nbsp; &nbsp; &nbsp; &nbsp; stack.push(nextInput );&nbsp; &nbsp; &nbsp; &nbsp; if (nextInput.equals(" ")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print(stack.pop() + " ");&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java