2014-02-28 322 views
0

提示用戶輸入2個自然數x和y。嵌套'for'循環

檢查這些數字是否在自然數集合中;如果不是,則退出。

打印所有數字對(x,y)。

例子:

對於x輸入一個自然數:3

爲y輸入一個自然數:2

(0,0),(0,1),(0,2) 
(1,0),(1,1),(1,2) 
(2,0),(2,1),(2,2) 
(3,0),(3,1),(3,2) 
There are 12 pairs. 

我知道我將需要使用如果的一些位置檢查,打印println使輸出看起來完全如圖所示。

這是我到目前爲止有:

Scanner scan = new Scanner (System.in); 
System.out.println("Enter a natural number for x: "); 
int x = scan.nextInt(); 
System.out.println("Enter a natural number for y: "); 
int y = scan.nextInt(); 


if (x>0 && y>0) 
{ 
    for (x = 0; x <= x ; x++) 
    { 
     for (y=0; y <= y ; y++) 
     { 
      System.out.println(x + " " + y); 
     } 
    } 
} 
else 
{ 
    System.exit(0); 
} 

我不知道如何從這裏走,我可以告訴大家,我的for循環最有可能不正確。

回答

1
for (int i = 0; i <= x; i++) { 
    for (int j = 0; j <= y; j++) 
     System.out.println("(" + i + ", " + j + ")"); 
} 
1
System.out.println("Enter a natural number for x: "); 
int x = scan.nextInt(); 
System.out.println("Enter a natural number for y: "); 
int y = scan.nextInt(); 


if (i>0 && j>0) 
{ 
    for (i = 0; i <= x ; i++) 
    { 
     for (j=0; j <= y ; j++) 
     { 
      System.out.print("("+i + ", " + j+")"); 
     } 
     System.out.println(""); 
    } 

} 
else 
{ 
    System.exit(0); 
} 

或者

System.out.println("Enter a natural number for x: "); 
int x = scan.nextInt(); 
System.out.println("Enter a natural number for y: "); 
int y = scan.nextInt(); 


if (i>0 && j>0) 
{ 
    for (i = 0; i <= x ; i++) 
    { 
     for (j=0; j <= y ; j++) 
     { 
      if(j != y){ 
       System.out.print("("+i + ", " + j+")"); 
      }else{ 
       System.out.println("("+i + ", " + j+")"); 
      } 
     } 

    } 

} 
else 
{ 
    System.exit(0); 
} 
+0

這是不對的,使用指數計數器從x和y的標識符在for循環不同,如@臘comadreja做 – Daniel