【问题标题】:System.out.println doesn't show text in console (IntelliJ)System.out.println 不在控制台中显示文本(IntelliJ)
【发布时间】:2018-01-13 16:32:34
【问题描述】:

我正在编写一个程序,其部分如下所示:

public class Portal {

    private String name;
    private int[] positions;              // positions of "ship"
    private static int moves = 0;         // moves made by player to sink a ship
    public static int shot;               // the value of position given by player
    private int hits = 0;                 // number of hits
    private int maxSize = 4;              // max size of ship (the size will be randomized)
    int first;                            // position of 1st ship block
    int size;                             // real size of ship (randomized in setPortal method)

    public void checkIfHit(){
        for (int i : positions){
            if (i == shot){
                System.out.println("Hit confirmed");
                hits++;
            } else if (hits == positions.length){
                System.out.println("Sunk");
            } else {
                System.out.println("Missed it");
            }
        }
        moves++;
    }

    public void setPortal(){
        size = 1 + (int)Math.random()*maxSize;
        for (int i = 0; i < size - 1; i++){
            if (i == 0){
                positions[i]= 1 + (int)Math.random()*positions.length;
                first = positions[i];
                System.out.println(positions[i]);
                continue;
            }
            positions[i]= first + 1;
            System.out.println(positions[i]);

        }
    }
}

public class Main{

    public static void main(String[] args){
        // write your code here
        Portal p1 = new Portal();
        p1.setPortal();
    }
}

代码分为两个 Java .class 文件。

我正在处理的问题是使用 p1.setPortal(); 不会在 IntelliJ 控制台中显示文本。该程序仍然有效并返回 0。 当我将 System.out.println 放入除 main 以外的方法(也在单独的类文件中)时,我在另一个程序中没有这样的问题。 出现此类问题的原因可能是什么?

【问题讨论】:

  • 不能保证setPortal 总是打印一些东西。 size 可以为 1,不会进入 for 循环。
  • 这正是问题的主要原因。我还将实施位置固定为“更随机”(我不正确地转换了类型,并且“大小”和“位置 [0]”的分数始终为 0。谢谢您的帮助。

标签: java intellij-idea


【解决方案1】:

它应该正确地抛出异常,因为您忘记初始化整数数组。 看看这个线程:Do we need to initialize an array in Java?

对于整数数组,Java 的默认值为 null。所以你的 for 甚至不会循环低谷。唯一让我感到奇怪的是为什么没有例外..

【讨论】:

  • 不,不应该,因为 java 有默认的构造函数会返回 null (NullPointerException),但是感谢 -rep @spandey15
  • @spandey15 不应该,因为它是一个实例变量,默认为null。这导致NullPointerException
猜你喜欢
  • 1970-01-01
  • 2015-05-04
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多