我目前停留在如何计算用户输入的连续数字上。我正在尝试执行a=lastvariable,但lastvariable保持为0。我知道变量范围,但是如何更改a=lastvariable



import java.util.Scanner;

public class Test {
    public static void main(String[]args){

        Scanner scan = new Scanner(System.in);

        System.out.print("Give a positive #: ");
        int input = scan.nextInt();
        int consecutive= 0;
        int lastvariable=0;


        while(input>0){
            System.out.print("Give a positive #: ");
            int a = scan.nextInt();
            if(a==lastvariable)
                 consecutive++;
            if (a<0)
                input = 0;
            a = lastvariable;
        }
        System.out.println("Consecutive #'s: " + consecutive);
    }

最佳答案

以此方式更改while循环。您犯了一个未设置lastvariable的小错误。

while(input>0){ System.out.print("Give a positive #: "); int a = scan.nextInt(); if(a==lastvariable) consecutive++; if (a<0) input = 0; lastvariable = a; //small correction here }

10-07 19:08