[英]Java: System.out.println() should write to the console, but it doesn't
[英]System.out.println doesn't show text in console (IntelliJ)
我正在編寫一個程序,其部分如下所示:
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 以外的方法中(也在單獨的類文件中)時,我在另一個程序中沒有這樣的問題。 造成此類問題的原因可能是什么?
它應該正確拋出異常,因為您忘記初始化整數數組。 看看這個線程: Do we need to initialize an array in Java?
對於整數數組,Java 的默認值為 null。 所以你的 for 甚至不會循環。 唯一讓我感到奇怪的是為什么沒有例外..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.