PDA

View Full Version : سوال: مشکل در ساخت مثلث اعداد ( خیام پاسکال)



drsina
شنبه 07 دی 1392, 13:44 عصر
سلام .
نمیدونم چرا این کد تا 5 تا رو به صورت درست شون میده ولی بیشتر از 5 رو نشون نمیده .
منطقم کاملا درسته و اررو Out of Bound برای آرایه میده .

توو Netbeans

package mosalas;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
a++;

String[][] array = new String[a][a + (a - 1)];

int je = 1;

float vasat = a / 2;

if (a % 2 != 0) {
vasat = (float) (vasat + 0.5);
}
int AddadVasat = (int) vasat;



for (int i = 1; i < a; i++) {

array[i][AddadVasat + 1] = i + "";

}


//////////////////////////////////////////////


for (int i = 1; i < a; i++) {

for (int j = 1; j < a; j++) {


if(j+i < array.length){


array[i + j][(AddadVasat + 1) - i] = j + "";
array[i + j][(AddadVasat + 1) + i] = j + "";
}



}

}





//////////////////////// show

for (int i = 0; i < a; i++) {
for (int j = 0; j < a + (a - 1); j++) {
if (array[i][j] == null) {
System.out.print("x\t");
} else {
System.out.print(array[i][j] + "\t");
}
}
System.out.println("");
}

}
}

drsina
شنبه 07 دی 1392, 14:45 عصر
سلام .
ممنون حل شد . این قطعه کد رو عوض کردم .

for (int i = 1; i < a; i++) {

for (int j = 1; j < a; j++) {


if (j + i < array.length) {

try {
array[i + j][(AddadVasat + je) - i] = j + "";
array[i + j][(AddadVasat + je) + i] = j + "";
} catch (Exception jh) {
System.out.println("_____________________________________________");
}
} else {
System.out.println(" Erooooooooooooooooooor");
}

a.seieddokht
شنبه 07 دی 1392, 17:27 عصر
سلام دوست عزیز منم این کد رو نوشتم دوست داشتی استفاده کن ساده نوشتم



public class PascalTriangle
{
private int fact(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * fact(n - 1);
}

private int combination(int n,int r)
{
return fact(n) / (fact(r) * fact(n - r));
}

public void print(int n)
{
for (int i = 0; i < n; i++)
{

for (int j = 1; j <= 2 * (n - i);j++)
{
System.out.print(" ");
}

for (int j = 0; j <= i; j++)
{
System.out.print(combination(i, j) + " ");
}

System.out.println();
}
}

public static void main(String[] args)
{
PascalTriangle pascalTriangle = new PascalTriangle();
pascalTriangle.print(5);
}
}



موفق باشید:لبخندساده: