此代码不是产生任何输出,而是在我使用“导入”的行上引发错误。效用。我不知道如何删除此错误。请帮忙!我是新手。我在' Head First Java'中读到了这段代码。由Sierra。
import java.util.*;
public class DotComBust {
private GameHelper helper = new GameHelper();
private ArrayList < DotCom > dotComsList = new ArrayList < DotCom > ();
private int numOfGuesses = 0;
private void setUpGame() {
DotCom one = new DotCom();
one.setName("pets.com");
DotCom two = new DotCom();
two.setName("toys.com");
DotCom three = new DotCom();
three.setName("go.com");
dotComsList.add(one);
dotComsList.add(two);
dotComsList.add(three);
System.out.println("sink all coms");
System.out.println("jk yhhg jyhhj ");
System.out.println("in small no of guesses");
for (DotCom dotComToSet: dotComsList) {
ArrayList < String > newLoction = helper.placeDotCom(3);
dotComToSet.setLocationCells(newLocation);
}
}
private void stratPlaying() {
while (!dotComsList.isEmpty()) {
String userGuess = helper.getUserInput("enter a number");
checkUserGuess(userGuess);
}
finishGame();
}
private void checkUserGuess(String userGuess) {
numOfGuesses++;
String result = "miss";
for (DotCom dotComToTest: dotComsList) {
result = dotComToTest.checkYourself(userGuess);
if (result.equals("hit")) {
break;
}
if (result.equals("kill")) {
dotComsList.remove(dotComToTest);
break;
}
}
System.out.println(result);
}
private void finishGame() {
System.out.println("all d are dead");
if (numOfGuesses <= 18) {
System.out.println("you took " + numOfGuesses);
System.out.println("u got out");
} else {
System.out.println("took u long " + numOfGuesses);
System.out.println("u are worst");
}
}
public static void main(String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
}
}
import java.util.*;
public class DotCom {
private ArrayList < String > locationCells;
private String name;
public void setLocationCells(ArrayList < String > loc) {
locationCells = loc;
}
public void setName(String n) {
name = n;
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index <= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
System.out.println("you sunk " + name);
} else {
result = "hit";
}
}
return result;
}
}
答案 0 :(得分:1)
您不应将所有内容都放在一个文件中。创建一个新文件DotCom
并粘贴下面的代码
import java.util.*;
public class DotCom {
private ArrayList < String > locationCells;
private String name;
public void setLocationCells(ArrayList < String > loc) {
locationCells = loc;
}
public void setName(String n) {
name = n;
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index <= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
System.out.println("you sunk " + name);
} else {
result = "hit";
}
}
return result;
}
}
请务必从DotComBust
删除上述代码。
1个Java源文件中不能存在2个相同的导入(import java.util.*; import java.util.*
)。您需要做的是将其拆分为2个源文件或删除第二个导入文件。