@RamBamBooOff
Чайник

Ошибка incompatible types: Object cannot be converted to. Как исправить?

Код из HeadFirst
Выглядит это так:
/DotComBust.java:5: error: cannot find symbol
private GameHelper helper = GameHelper();//нужные переменные
^
symbol: method GameHelper()
location: class DotComBust
/DotComBust.java:19: error: incompatible types: Object cannot be converted to DotCom
for (DotCom dotComToSet:dotComList){//повторяем с каждым dotcom
^
/DotComBust.java:35: error: incompatible types: Object cannot be converted to DotCom
for (DotCom dotComToTest : dotComList){//сделать это для всех dotcom в списке
^
Note: /DotComBust.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
3 errors

import java.io.*;
import java.util.ArrayList;
import java.util.*;
public class DotComBust{
    private GameHelper helper = GameHelper();//нужные переменные
    private ArrayList dotComList = new ArrayList();//ArrayList только для сайтов
    private int numOfGuesses = 0;
    private void setUpGame(){//создаем сайты и даем им имена
        DotCom one = new DotCom();
        one.setName("Pets.com");
        DotCom two = new DotCom();
        two.setName("eToys.com");
        DotCom three = new DotCom();
        three.setName("Go2.com");
        dotComList.add(one);//помещаем их в ArrayList
        dotComList.add(two);
        dotComList.add(three);
        System.out.println("Потопить 3");//инструкции
        for (DotCom dotComToSet:dotComList){//повторяем с каждым dotcom
            ArrayList<String> newLocation = helper.placeDotCom(3);//зарпашиваем у объекта адрес сайта
            dotComToSet.setLocationCells(newLocation);//вызываем сеттер из dotcom
        }//и передаем ему местоположение корабля, которое
    }//только что получили от другого объекта
    private void startPlaying(){
       while(!dotComList.isEmpty()){ //делать это(далее), пока dotcom не опустеет
           String userGuess = helper.getUserInput("Сделайте ход"); //ход пользователя
           checkUserGuess(userGuess); //проверяем на факт попадания
       }
       finishGame();
    }

    private void checkUserGuess(String userGuess){
        numOfGuesses++;//плюс попытка
        String result = "Мимо";//изначально это мимо
        for (DotCom dotComToTest : dotComList){//сделать это для всех dotcom в списке
            result = dotComToTest.checkYourself(userGuess);//проверяем было ли попадание
            if(result.equals("Попал")){//если да, то...
                break;//останавливаем цикл и ждем следующий ход
            }
            if(result.equals("Потопил")){
                dotComList.remove(dotComToTest);//если потоплен, то удаляем
                break;//из списка и останавливаем цикл
            }
        }
        System.out.println(result);//результат выстрела
    }
    private void finishGame(){
        System.out.println("Все сайты на дне, упс");
        if(numOfGuesses <= 18){
            System.out.println("Отлично " + numOfGuesses);//итог всей игры
        } else {
            System.out.println("Плохо " + numOfGuesses);
        }
    }
    public static void main(String[] args){
        DotComBust game = new DotComBust();//создаем игровой объект
        game.setUpGame();//объявляем подготавливаем игру
        game.startPlaying();//начинаем игру
    }
}
class DotCom{
    private ArrayList<String> locationCells;//местоположение
    private String name;//имя сайта
    public void setLocationCells(ArrayList<String> loc){//обновляет местоположение
        locationCells = loc;//сайта, полученый случайно из placeDotCom()
    }
    public void setName(String n){//"Ваш простой сеттер"
        name = n;
    }
    public String checkYourself(String userInput){
        String result = "Мимо";//если есть попадание, то indexOf вернет его местоположение
        int index = locationCells.indexOf(userInput);//если мимо, то вернет -1
        if (index >= 0){//если попал, то удаляем ячейку по индексу
            locationCells.remove(index);
            if (locationCells.isEmpty()){//если сайт "пуст", то потопил
                result = "Потопил";
                System.out.println("Потоплен " + name);//поздравление
            }else{
                result = "Попал";
            }
        }
        return result;
    }
}
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();
    }
    public ArrayList<String> placeDotCom(int comSize){
        ArrayList<String> alphaCells = new ArrayList<String>();
        String [] alphacoords = new String [comSize];
        String temp = null;
        int [] coords = new int[comSize];
        int attempts = 0;
        boolean success = false;
        int location = 0;
        comCount++;
        int incr = 1;
        if((comCount % 2) == 1){
            incr = gridLength;
        } 
        while (!success & attempts++ < 200){
            location = (int)(Math.random()*gridSize);
            System.out.print("пробуем " + location);
            int x = 0;
            success = true;
            while (success && x < comSize){
                if(grid[location] == 0){
                    coords[x++] = location;
                    location += incr;
                    if(location >= gridSize){
                        success = false;
                    }
                    if(x>0 && (location % gridLength == 0)){
                        success = false;
                    }
                } else {
                    System.out.print(" используется " + location);
                    success = false;
                }
            }
        }
        int x = 0;
        int row = 0;
        int column = 0;
        while (x < comSize){
        grid[coords[x]] = 1;
        row = (int)(coords[x]/gridLength);
        column = coords[x]%gridLength;
        temp = String.valueOf(alphabet.charAt(column));
        alphaCells.add(temp.concat(Integer.toString(row)));
        x++;
        System.out.print(" coord " + x + alphaCells.get(x-1));
        }
    
   
   return alphaCells;
    }
    
}

Не ругайтесь, я же чайник, мне можно ошибаться
  • Вопрос задан
  • 2591 просмотр
Решения вопроса 1
zagayevskiy
@zagayevskiy Куратор тега Java
Android developer at Yandex
new GameHelper();

ArrayList< DotCom> dotComList = new ArrayList<>()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
02 мая 2024, в 13:02
15000 руб./за проект
02 мая 2024, в 12:58
7000 руб./за проект
02 мая 2024, в 12:58
6500 руб./за проект