zacal som sa učiť kodit v Jave knihou Head First Java.
Mam len malé skúsenosti s programovaním, tobôž s OO (par riadkov kodu v Pascale, Lazaruse).
Všetkému som zatiaľ rozumel, až kým som prišiel k tomúto príkladu:
Pri používaní klasických polí mi všetko fungovalo, no keď som sa ho snažil prerobiť na ArrayList, najúspešnejšie bolo, keď císla čítalo, no vôbec ich neporovnáva a tým padom vždy je výsledok "miss".
Dúfam, že Vás môj opis problému veľmi nezmiatol, prvykrát žiadam o radu, čo sa týka programovanie, a preto je asi aj moja otázka dosť divná, v prípade potreby upresním (ak budem vedieť, na čo sa pýtate.
Prikladám aj zdrojový kód triedy DotCom a GameHelper.
Kód: Vybrať všetko
package simpledotcom;
import java.util.ArrayList;
public class DotCom {
private static ArrayList<String> locations = new ArrayList<>();
private ArrayList<String> locationCells = new ArrayList<>();
String guess;
public static void main (String[] args) {
int numberOfGuesses = 0;
GameHelper helper = new GameHelper();
DotCom theDotCom = new DotCom();
int randomNum = (int) (Math.random() * 5);
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while (isAlive){
String userInput = helper.getUserInput("Enter a number");
String result = theDotCom.checkYourself(userInput);
System.out.println(result);
}
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}
else {
result = "hit";
}
}
return result;
}
public void setLocationCells(ArrayList<String> loc){
locationCells = loc;
}
}Kód: Vybrať všetko
package simpledotcom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameHelper {
private static final String alphabet = "abcdefg";
private int gridLength = 7;
private int gridSize = 49;
private int [] grid = new int[gridSize];
private int comCount = 0;
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase();
}
}