Java 图形误差校正
我试着打印这个模式,正如我在代码中所展示的。但是不知怎么的,我不知道我犯了什么错误,这个wierd输出和期望的输出一起出现了。如果你们能帮助我,我将非常感激Java 图形误差校正,java,arrays,function,Java,Arrays,Function,我试着打印这个模式,正如我在代码中所展示的。但是不知怎么的,我不知道我犯了什么错误,这个wierd输出和期望的输出一起出现了。如果你们能帮助我,我将非常感激 /*2 6 12 20 30 42 * 4 6 8 10 12 * 2 2 2 2 * 0 0 0 * 0 0 * 0 * */ public class patt { static int ar[]={2,6,12,20,30,42}; public static void pattern(){
/*2 6 12 20 30 42
* 4 6 8 10 12
* 2 2 2 2
* 0 0 0
* 0 0
* 0
*
*/
public class patt {
static int ar[]={2,6,12,20,30,42};
public static void pattern(){
int y=0,x=0;
while( x<ar.length){
int c[]=new int[6];
if(x+1>=ar.length){
break;
}
else{
c[x]=ar[x+1]-ar[x];
System.out.print(c[x]+" ");
ar[x]=c[x];
}
x++;
}
System.out.println();
}
public static void main(String args[]){
patt ob=new patt();
System.out.println("2 6 12 20 30 42");
for(int a=0;a<6;a++){
ob.pattern();
}
}
}
The output is as follows,
2 6 12 20 30 42
4 6 8 10 12
2 2 2 2 30
0 0 0 28 12
0 0 28 -16 30
0 28 -44 46 12
28 -72 90 -34 30
/*2 6 12 20 30 42
* 4 6 8 10 12
* 2 2 2 2
* 0 0 0
* 0 0
* 0
*
*/
公共类patt{
静态int ar[]={2,6,12,20,30,42};
公共静态void模式(){
int y=0,x=0;
while(x=ar.length){
打破
}
否则{
c[x]=ar[x+1]-ar[x];
系统输出打印(c[x]+“”);
ar[x]=c[x];
}
x++;
}
System.out.println();
}
公共静态void main(字符串参数[]){
patt ob=新patt();
系统输出println(“2 6 12 20 30 42”);
对于(int a=0;a您将运行函数6次(作为数组的长度)。
问题是您将更改保留在静态数组中,但随后运行以下条件:
if(x+1>=ar.length){
break;
}
以上对于第一次运行来说是可以的。但是在第一次运行之后,应该剩下5个元素(在对元素进行差异处理之后)。但是,您将始终按照数组的整个长度运行。这解释了为什么您总是在每行上打印5个元素。
您的解决方案是定义另一个静态数组,即长度,然后在每次运行后减小该长度。
我添加了一个静态长度变量,替换了上面列出的条件以查看它,而不是始终查看数组长度,并在每次运行时减少了该变量
public class patt {
static int ar[]={2,6,12,20,30,42};
static int length=ar.length;
public static void pattern(){
int y=0,x=0;
while( x<ar.length){
int c[]=new int[6];
if(x+1>=length){
break;
}
else{
c[x]=ar[x+1]-ar[x];
System.out.print(c[x]+" ");
ar[x]=c[x];
}
x++;
}
System.out.println();
length--;
}
public static void main(String args[]){
patt ob=new patt();
System.out.println("2 6 12 20 30 42");
for(int a=0;a<6;a++){
ob.pattern();
}
}
}
公共类patt{
静态int ar[]={2,6,12,20,30,42};
静态int长度=ar.length;
公共静态void模式(){
int y=0,x=0;
while(x=长度){
打破
}
否则{
c[x]=ar[x+1]-ar[x];
系统输出打印(c[x]+“”);
ar[x]=c[x];
}
x++;
}
System.out.println();
长度--;
}
公共静态void main(字符串参数[]){
patt ob=新patt();
系统输出println(“2 6 12 20 30 42”);
对于(int a=0;a