简体   繁体   English

简单的数组插入程序产生错误的输出

[英]Simple Array Insertion Program Producing Incorrect Output

Here's an extremely simple java program where I declare any array with 7 elements, input the first six, move the fourth to sixth elements to the fifth to seventh positions, and obtain a value for the fourth empty position: 这是一个非常简单的Java程序,我在其中声明具有7个元素的任何数组,输入前六个元素,将第四至第六个元素移至第五至第七个位置,并获得第四个空位置的值:

int A[]=new int[7];
        for(int i=0;i<6;i++)
        {
            System.out.println("Enter an integer");
            String a=Biff.readLine();
            A[i]=Integer.parseInt(a);
        }
        for(int i=4;i<6;i++)
        {
            A[i]=A[i+1];
        }
        System.out.println("Enter the integer to be inserted");
        String a=Biff.readLine();
        A[4]=Integer.parseInt(a);

However, when all array elements are printed, the sixth and seventh positions are 0, and I have no idea why. 但是,当打印所有数组元素时,第六和第七位置为0,我不知道为什么。 Reasons and fixes will be greatly appreciated. 原因和修复将不胜感激。 Note: I can't use any array methods, have to keep it very simple. 注意:我不能使用任何数组方法,必须使其非常简单。

  • Input: 1,2,3,4,5,6; 输入:1,2,3,4,5,6; Then 1; 然后1;
  • Desired Output: 1,2,3,4,5,1,6; 所需输出:1,2,3,4,5,1,6;
  • Actual Output: 1,2,3,4,1,0,0; 实际输出:1,2,3,4,1,0,0;

Your initial loop is not assigning anything to the 7th element, so it remains 0. 您的初始循环未为第7个元素分配任何内容,因此它保持为0。

And later you copy the 7th element to the 6th one 然后将第7个元素复制到第6个元素

 A[i]=A[i+1];

so both the 6th and 7th elements should be 0. 因此第6个和第7个元素都应为0。

Change the loop to : 将循环更改为:

    for(int i=0;i<A.length;i++)
    { //         ^^^^^^^^^------------------------ change is here
        System.out.println("Enter an integer");
        String a=Biff.readLine();
        A[i]=Integer.parseInt(a);
    }

You are moving the values in the wrong way. 您以错误的方式移动值。 Use this code and understand your mistake: 使用此代码并了解您的错误:

for(int i=6;i>=3;i--)    //Moving the 4th to 6th elements to 5th to 7th elements
    {
        A[i]=A[i-1];
    }
String a=Biff.readLine();    //Taking input for 4th empty position
A[3]=Integer.parseInt(a);

I hope I got your question right. 希望我能正确回答你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM