Keyone808 2022-03-19 14:47 采纳率: 50%
浏览 23

再写一个猜数字的程序,用到Scanner和arraylist的API 用的是JAVA


import java.util.Scanner;
import java.util.ArrayList;


class SimpleDotcomtestDrive {//测试开发代码
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        SimpleDotcom dot = new SimpleDotcom();
        int randomNum = (int)(Math.random()*10);//产生任意数
        int n =1;
        ArrayList<String> location = new ArrayList<String>();//建立arraylist
        String a = new String(" "+(randomNum+1));/*储存正确答案*/
        location.add(a);
        String b = new String(""+(randomNum+2));
        location.add(b);
        String c = new String(""+(randomNum));
        location.add(c);
        dot.setlocationcells(location); //设置
        System.out.println("请输入一个0到10的数字: ");
        String user_Guess = scanner.nextLine();//输入数字
        String result =dot.checkYouself(user_Guess);
        while(true){
            if(result.equals("kill")){
                System.out.println("You took "+ n +"  guesses");
                break;
            }else{
                System.out.println("请输入一个0到10的数字: ");
                String user_Guess00 = scanner.nextLine();
                n=++n;
                result = dot.checkYouself(user_Guess00);
            }
        }

    }
}



/*实际代码*/

public class SimpleDotcom {
    private ArrayList<String> locationcells;

    public void setlocationcells(ArrayList<String> loc) {
       locationcells = loc;//获取值
    }

    public String checkYouself(String a){
        int guess = Integer.parseInt(a);//将字符串转化为数字
        int index = locationcells.indexOf(guess);//返回a的位置
        String result ="miss";//初始胡result
        if(index>=0){ //有匹配的数
            locationcells.remove(index); //删除匹配数字
            if(locationcells.isEmpty()){
                result = "kill";
            }else {
                result = "hit";
            }
        }
        System.out.println(result);
        return result;
    }
}

结果问题就是好像没有正确答案,我DEbug的时候发现传输arraylist到另一个对象的时候,字符串消失了,好像这样不能传一样,不管我猜啥数字都无法猜中正确答案。
  • 写回答

1条回答 默认 最新

  • 追风中的小少年 2022-03-19 15:21
    关注

    img

    你在用int 类型的 guess在String类型的locationcells中indexOf是永远找不到的

    评论

报告相同问题?

问题事件

  • 创建了问题 3月19日

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程