简体   繁体   中英

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:

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();
    }
}

code is split in two Java .class files.

The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0. I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file). What may be the cause of such issue?

It should properly throw an exception, because you forgot to initialize the integer array. Have a look at this thread: Do we need to initialize an array in Java?

The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM