【发布时间】: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