因此,我想在每次循环时将变量rolltotal与自身一起添加。

    Random ran = new Random();
    int roll;
    int rolltotal;
    Scanner s= new Scanner(System.in);
    roll=s.nextInt();
    while(roll!=-1) {
        int die1 = ran.nextInt(6)+1;
        int die2 = ran.nextInt(6)+1;
        int die3 = ran.nextInt(6)+1;
        int die4 = ran.nextInt(6)+1;
        int die5 = ran.nextInt(6)+1;
        int die6 = ran.nextInt(6)+1;
        rolltotal=die1+die2+die3+die4+die5+die6;
        System.out.println(rolltotal);
        int a;
        a=rolltotal+rolltotal;
        System.out.println(a);
        roll=s.nextInt();
    }


我不知道该如何解释,希望您理解我的意思。所以可以说我有20个,循环之后有18个。如何将这两个数字相加。

最佳答案

在循环外跟踪rolltotal引用,并在循环的eo处获取循环内的临时sum变量,以更新rolltotal=rolltotal+tempSum

Random ran = new Random();
    int roll;
    int rolltotal;
    Scanner s= new Scanner(System.in);
    roll=s.nextInt();
    while(roll!=-1) {
        int die1 = ran.nextInt(6)+1;
        int die2 = ran.nextInt(6)+1;
        int die3 = ran.nextInt(6)+1;
        int die4 = ran.nextInt(6)+1;
        int die5 = ran.nextInt(6)+1;
        int die6 = ran.nextInt(6)+1;
        int tempSum=die1+die2+die3+die4+die5+die6;
        System.out.println(tempSum);
        rolltotal=rolltotal+tempSum;
        System.out.println(rolltotal);
        roll=s.nextInt();
    }

10-04 11:47