初次尝试建立Android软件

建立Android软件前的准备:安装Android studio(JDK已安装)
安装Android studio的教程在网络很多,很容易查到。
安装后,添加新项目,语言选择java。
在java文件夹里创建:
Station.java:
public class Station {
private String name;
private List lines;

public Station(String name) {
this.name = name;
this.lines = new ArrayList<>();
}

public String getName() {
return name;
}

public void addLine(String line) {
if (!lines.contains(line)) {
lines.add(line);
}
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Station station = (Station) o;
return name.equals(station.name);
}

@Override
public int hashCode() {
return name.hashCode();
}
}

Line.java:
public class Line {
private String name;
private List stations;

public Line(String name) {
this.name = name;
this.stations = new ArrayList<>();
}

public void addStation(Station station) {
stations.add(station);
station.addLine(this.name);
}

public List getStations() {
return stations;
}

public String getName() {
return name;
}
}

MetroSystem.java:
import java.util.*;

public class MetroSystem {
private Map<String, Station> stations = new HashMap<>();
private List lines = new ArrayList<>();
private Map<Station, List> adjacencyList = new HashMap<>();

public void addLine(String lineName, List stationNames) {
Line line = new Line(lineName);
List lineStations = new ArrayList<>();

for (String name : stationNames) {
Station station = stations.get(name);
if (station == null) {
station = new Station(name);
stations.put(name, station);
}
station.addLine(lineName);
line.addStation(station);
lineStations.add(station);
}

lines.add(line);
buildAdjacency(lineStations);
}

private void buildAdjacency(List stations) {
for (int i = 0; i < stations.size(); i++) {
Station current = stations.get(i);
adjacencyList.putIfAbsent(current, new ArrayList<>());

if (i > 0) {
Station prev = stations.get(i - 1);
adjacencyList.get(current).add(prev);
adjacencyList.get(prev).add(current); // 双向连接
}
}
}

public int calculateFare(String start, String end) {
Station startStation = stations.get(start);
Station endStation = stations.get(end);

if (startStation == null || endStation == null) return -1;

int stops = bfs(startStation, endStation);
if (stops == -1) return -1;

return (int) Math.ceil(stops / 3.0);
}

private int bfs(Station start, Station end) {
Queue queue = new LinkedList<>();
Map<Station, Integer> distances = new HashMap<>();

queue.add(start);
distances.put(start, 0);

while (!queue.isEmpty()) {
Station current = queue.poll();
if (current.equals(end)) return distances.get(current);

for (Station neighbor : adjacencyList.getOrDefault(current, new ArrayList<>())) {
if (!distances.containsKey(neighbor)) {
distances.put(neighbor, distances.get(current) + 1);
queue.add(neighbor);
}
}
}
return -1;
}

public List getStationNames() {
return new ArrayList<>(stations.keySet());
}
}

在activity_main.xml文件里:

posted @ 2025-03-14 20:30  老汤姆233  阅读(33)  评论(0)    收藏  举报