import java.util.Scanner;
/*题目描述:(战舰游戏一)有一种棋牌类的战舰游戏,目标是要猜测对方战舰的坐标,然后轮流开炮攻击,命中数发就可以打沉对方的战舰。现在我们先在做一个简单的战舰游戏
首先创建一个SimpleDotCom类,需要一个记录战舰位置的locationCells数组成员变量;创建一个获取主函数中输入发射位置的方法setLocationCells;
然后创建一个用于判断是否击中checkYourself的方法,在checkYourself方法中创建一个Sting类型的result局部变量,初始化result的值为"miss",如果命中则为hit;
输入一共有三行,第一行为战舰的数量
第二行为战舰的位置
第三行为用户攻击的位置(String类型)
输出为一个字符串(判断是否击沉)
/
/*测试输入:3
2 3 4
测试输出:hit
/
public class SimpleDotComTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner num = new Scanner(System.in);
int n;
n = num.nextInt();
int[] locations = new int[n];
for(int i=0;i<n;i++){
locations[i] = num.nextInt();
}
SimpleDotCom dot = new SimpleDotCom();
dot.setLocationCells(locations);
String userGuess = num.next();
String result = dot.checkYourself(userGuess);
}
}
/*测试数据:
1 2 3
2
1 2 3
4
我按你的描述大概写了个程序,你看下能满足不
import java.util.ArrayList;
public class SimpleDotCom {
private ArrayList<Integer> locationCells; // 用于存储战舰的位置
public void setLocationCells(ArrayList<Integer> cells) {
locationCells = cells;
}
public String checkYourself(String guess) {
String result = "miss"; // 初始化为“miss”,表示未击中
int index = locationCells.indexOf(Integer.parseInt(guess)); // 查找用户猜测的位置是否与战舰位置匹配
if (index >= 0) { // 如果匹配
locationCells.remove(index); // 从列表中移除命中的位置
if (locationCells.isEmpty()) { // 如果所有战舰都已经被击沉
result = "kill"; // 则返回“kill”,表示击沉
} else {
result = "hit"; // 否则返回“hit”,表示命中但是未击沉
}
}
return result; // 返回结果
}
}
以下是添加注释后的测试程序:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numShips = scanner.nextInt(); // 获取战舰数量
scanner.nextLine(); // 读取数字后的换行符
String[] shipLocations = scanner.nextLine().split(" "); // 获取战舰位置,每个位置用空格分隔
ArrayList<Integer> locations = new ArrayList<>(); // 创建一个 ArrayList,用于存储战舰的位置
for (String location : shipLocations) { // 将字符串数组转换为整数列表
locations.add(Integer.parseInt(location));
}
SimpleDotCom dotCom = new SimpleDotCom(); // 创建 SimpleDotCom 对象
dotCom.setLocationCells(locations); // 设置战舰位置
String guess = scanner.nextLine(); // 获取用户猜测的位置
String result = dotCom.checkYourself(guess); // 判断是否命中
System.out.println(result); // 输出结果
}
}
在这个测试程序中,首先获取战舰数量。然后,读取数字后的换行符,以便在下一行读取战舰位置。使用 split
方法将字符串分割为一个字符串数组,然后将其转换为整数列表。接下来,创建一个 SimpleDotCom
对象,并将战舰位置设置为之前获取的位置。然后,获取用户猜测的位置,并调用 checkYourself
方法来判断是否命中。最后,将结果打印到控制台上。
如果我的回答,对你有帮助,麻烦关注一下,也可以继续提问,谢谢