java - 变量 j 的值如何增加到 6

标签 java

实际上,整个代码的目的是获取数组中的输入值(0或1),然后检查输入的数组中是否有6个连续的0,然后在每6个连续的0之后插入“1”。我发现这个 block

if(j>5){
        shift(i+6);
        bits[i+6] = 1;
        count+=1;
        System.out.println(count);
}
即使输入的数组中没有 6 个连续的 0,

也会执行。然后去检查问题。我添加了这个声明

 System.out.println("ABHINAV " + j ); 

这是输出:-

Entered Bits are:  
 1
 0
 1
 0
 1
 0
 1
 0
 1
 0
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 6

我发现了问题 - 变量“j”增加到 6,因此进入了“if” block 。我的问题是:-

“j”如何增加到 6(正如您可以看到输出快照的最后一行)。

如何解决这个问题。我做错了什么。

这是完整的代码

class Stuff{
    public static final int LENGTH=6;                  
    public int count=0;             
    int n;
    public int bits[] = new int[40]; 
    Scanner inputs = new Scanner(System.in);
    Stuff(int x){
        n=x;
    }
    public void input(){
        for(int i=0 ; i<n ; i++){
            bits[i] = inputs.nextInt();
        }
    }
    public void len_check(){
        int j=0;
        for(int i = 0 ; i< n ; i++){
                j=0;
                while(bits[i+j] == 0 && j<LENGTH){
                    j+=1;
                }
                System.out.println("ABHINAV " + j );
                if(j>5){
                    shift(i+6);
                    bits[i+6] = 1;
                    count+=1;
                    System.out.println(count);
                }
        }
    }   
    public void shift(int u){
        for(int i=n ; i>= u ;i--){
            bits[i+1] = bits[i];
        }
    }   
    public void display(){
        for(int i=0 ; i<n+count ; i++){
            System.out.println(" " + bits[i]);
        }
    }
}

class Problem{
    public static void main(String args[]){
        int n;
        Scanner inputs = new Scanner(System.in);
        System.out.println("\nEnter bit stream length");
        n = inputs.nextInt();
        Stuff stuff = new Stuff(n);
        System.out.println("Now Enter the bits: ");
        stuff.input();                  // Enter the bit stream 
        System.out.println("Entered Bits are:  ");
        stuff.display();    
        stuff.len_check();
        System.out.println("Altered Bits are: ");
        stuff.display();
    }
}

最佳答案

这是因为输入只有 10 个位置长,在前 10 个值之后,数组 bits 被填充为 0 (标准值)。 它按照编程工作,从位置 10 开始找到 6 0

到达位置n - 5时应该停止,例如:

...
int j = 0;
for (int i = 0 ; i< n-5 ; i++) {
    j = 0;
...

关于java - 变量 j 的值如何增加到 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981332/

相关文章:

java - 当我尝试从 play 框架访问我​​的数据库(MySQL)时,我在编码 :"The import play.db cannot be resolved"时收到此错误

java - 多态性——构造相同类型的对象

Java不会使用parseInt

java - 映射属性具有相同类型的 jpa 关系

java - 将 bean 注入(inject)到 Spring 托管上下文之外的类中

java - Liquibase,本地 XSD 引用

java - 使用数据库函数的JPA查询使用特定索引

java - 跳过发送 Junit 中的方法参数之一

java - 从字符串 kotlin 中提取数字

java - 当其他任务完成时,强制 BufferedWriter 从 BlockingQueue 写入