【问题标题】:Counting consecutive numbers计算连续数字
【发布时间】:2015-09-26 20:52:16
【问题描述】:

我目前被困在如何计算用户输入的连续数字上。我正在尝试做a=lastvariablelastvariable 保持为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);
    }

【问题讨论】:

  • 感谢您的帮助!
  • a = lastvariable 表示“将lastvariable 的值放入a”。
  • 第一次获得输入时(不在while 循环中),您没有将该值分配给lastvariable,不确定这是不是故意的。

标签: java loops scope


【解决方案1】:

以这种方式更改您的 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 }

【讨论】:

    【解决方案2】:

    试试这个:

    if (a<0) input = 0;
    lastvariable = a;
    

    【讨论】:

    • 请添加一些关于如何解决问题的描述。
    【解决方案3】:

    您永远不会将 lastvariable 设置为其他值。

        a = lastvariable;
    

    表示您将 a 设置为存储在 lastvariable 中的值,但反之则不然。

    【讨论】:

      【解决方案4】:
      a = lastvariable;
      

      a 分配给lastvariable 的值,在您当前的代码中,该值将始终为0。你必须这样做:

      lastvariable = a;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 2022-01-24
        • 2012-04-11
        • 2019-05-05
        • 1970-01-01
        相关资源
        最近更新 更多