【问题标题】:Why does System.out.println(String) not print anything?为什么 System.out.println(String) 不打印任何东西?
【发布时间】:2017-03-17 23:26:22
【问题描述】:

我的 java IDE 中有一些代码,我相信它支持控制台。我以前用过java,知道来龙去脉。但是,我以前没有出现过这个问题。我的代码如下所示:

    Scanner scanner = new Scanner(System.in);
    int choice = scanner.nextInt();

    System.out.println("Choose a class.");
    TimeUnit.SECONDS.sleep(10);
    System.out.println("Press 1 for the a class.");
    TimeUnit.SECONDS.sleep(10);
    System.out.println("Press 2 for the b class.");
    TimeUnit.SECONDS.sleep(10);
    System.out.println("Press 3 for the c class.");
    TimeUnit.SECONDS.sleep(10);

    switch(choice) {
        case 1:
            playerClass.chosenClass = "a";
            break;
        case 2:
            playerClass.chosenClass = "b";
            break;
        case 3:
            playerClass.chosenClass = "c";
            break;
        default:
            System.out.println("Null class. Please press 1-3 to choose a player class.");
    }
}

我有所有的导入,playerClass 类确实存在。问题是,“System.out.println(String)”不起作用。

【问题讨论】:

  • 我以前用过java,知道其中的来龙去脉——>进出之间好像少了点什么。
  • 在提出新问题之前,请务必阅读minimal reproducible example 指导。 IE。对于这个问题,证明问题的 2 行可能会在不问问题的情况下向您展示问题所在。
  • 知道了。但无法删除。
  • 而且,Sundararaj,是的,可能是这样。我有一年没学过Java了。我想这是其中一项技能,如果不使用会随着时间的推移而退化。

标签: java string


【解决方案1】:

您在接受输入后打印提示。由于您还没有看到提示,您可能没有输入任何输入。所以你永远不会超过Scanner.nextInt()

您的代码没有意义。

【讨论】:

  • 明白,不要使用 Scanner 类。
  • 顺便说一句,我不需要你告诉我我的代码没有意义。因为它没有。我知道。这就是我来这里的原因。想想看。如果计算机无法读取我的代码,我是否会认真地来到这里认为我的代码完全有意义?我只是在发帖前写的。
【解决方案2】:

您可能想要做的是将您的逻辑设置得更像:

System.out.println("Press 1 for xx, 2 for xx, or 3 for xx");

if(scanner.hasNext()){
    choice = scanner.Int();
}

if(choice == 1){
     //do whatever;
}
else if(choice == 2){
     //do whatever;
}

我可能没有正确理解您的问题,但我认为您需要确保一切井井有条。

【讨论】:

  • 是的。这就是我所做的,正如 EJP 所展示的那样,它确实有帮助。虽然你似乎对它不那么挑剔了。谢谢,顺便说一句。关于不像 EJP 那样重要。
猜你喜欢
  • 2012-12-30
  • 2014-07-03
  • 1970-01-01
  • 2011-05-27
  • 2011-10-27
  • 2019-02-20
  • 1970-01-01
  • 2013-04-06
  • 2019-05-18
相关资源
最近更新 更多