Home > Net >  random Strings in ArrayList
random Strings in ArrayList

Time:09-26

I bought Head First Java book, and i am trying to do the exercise sink a startup.

After a while the book introduce ArrayList, and show how to use it in the class and its' method.

Problem is once i change everything with arraylist, the MAIN doesn't work, becasue at start i used simple INT, in the array location, now it need array.

How can i change the values of INT into a type that i can put inside the array ?

thx for help, and here the code.

the class with the method:

private ArrayList<String> locationCells;
private int numOfHits = 0;


public void setLocationCells(ArrayList<String> locationCells) 
{
    this.locationCells = locationCells;
}


    public String checkYourself(String guess) {
    // creazione stringa miss
        String result = "miss";
        
        int index = locationCells.indexOf(guess);
        
        if (index >= 0) {
            
            locationCells.remove(index);
        }   
    
            
            if (locationCells.isEmpty()) {
                result = "kill";
                numOfHits   ;
                                
            }else 
                result = "hit";

        System.out.println(result);
        return result;
        
    }

and here the MAIN:

public static void main(String[] args) {
        
     java.util.Random randomGenerator = new java.util.Random();
     Scanner scan = new Scanner(System.in);
    
     
     StartUpCorretta dot = new StartUpCorretta();

    
    int manyGuesses = 0;
    
    boolean isAlive = true;
    
    
    int randomNumbers = randomGenerator.nextInt(5)  1;
    
    
    int randomNumb = (int) (Math.random() * 5);
    
    
    ArrayList<String> location = {randomNumbers,randomNumbers  1,randomNumbers  2};
    
    dot.setLocationCells(location);

    while(isAlive) {
        
        System.out.println("enter a number");
        int guess = scan.nextInt();
        
        String result = dot.checkYourself(guess);
        
        manyGuesses    ;
        
        if (result.equals("kill")) {
            isAlive = false;
            
        System.out.println("you took"   " "   manyGuesses   " "   "guesses");
        }
    
    }
    
    
}

CodePudding user response:

Seems, you are taking your input from console as int from this statement int guess = scan.nextInt();

So, my answer is based on your input data type.

Please, changed your arraylist generic type String to Integer And Secondly, this is not how you can initialized the arraylist

ArrayList<String> location = {randomNumbers,randomNumbers  1,randomNumbers  2};

Correct way to create collection using new operator like this

ArrayList<Integer> location = new ArrayList<>();

and correct way to add element into arraylist like this

location.add(randomNumbers);
location.add(randomNumbers 1);
location.add(randomNumbers 2);

Hope, it will work for you.

  • Related