【问题标题】:System.out.println() is not getting executed [duplicate]System.out.println() 没有被执行[重复]
【发布时间】:2021-03-05 22:46:38
【问题描述】:
import java.util.Scanner;
public class testFixedCapacityStack {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        FixedCapacityStack<String> s;
        s = new FixedCapacityStack<String>(100);

       while(sc.hasNext()) {

           String item = sc.next();
           if(!item.equals("-")) {
               s.push(item);
           } else if (!s.isEmpty()) {
               System.out.print(s.pop() + " ");
           }
       }
        System.out.println(s.size());
    }

}

我不知道为什么最后一行没有被执行。有人请指出我哪里做错了。 谢谢。

【问题讨论】:

  • @Tom 是的!谢谢

标签: java stack


【解决方案1】:

您的代码正在请求一个新字符串作为输入,如果它不为空,则继续循环。这使您的 while 循环成为一个永无止境的循环。这就是最后一行没有执行的原因。您可以在退出字符串的循环中插入 if 语句。

import java.util.Scanner;
public class testFixedCapacityStack {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        FixedCapacityStack<String> s;
        s = new FixedCapacityStack<String>(100);

       while(sc.hasNext()) {

           String item = sc.next();
           if(item.equals("/")) {
               break;
           }
           if(!item.equals("-")) {
               s.push(item);
           } else if (!s.isEmpty()) {
               System.out.print(s.pop() + " ");
           }
       }
        System.out.println(s.size());
    }

}

现在,当您输入值“/”作为输入时,它将退出 while 循环并执行最后一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多