[英]Nested 'for' loops
Prompts the user for 2 natural numbers x and y. 提示用户输入2个自然数x和y。
Checks if those numbers are in the set of natural numbers; 检查这些数字是否在自然数集中; exits if they are not. 如果他们不是退出。
Prints all pairs of numbers up to (x,y). 打印所有数字对(x,y)。
Example: 例:
Enter a natural number for x: 3 输入x:3的自然数
Enter a natural number for y: 2 输入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.
I know I will need to use some placement of if checks, print and println to get the output to look exactly as shown. 我知道我需要使用if check, print和println的一些放置来使输出看起来完全如图所示。
this is what I have so far: 这是我到目前为止:
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);
}
I am not sure how to go on from here, I can tell that my for loops are most likely incorrect. 我不知道如何从这里继续,我可以告诉我的for循环很可能是不正确的。
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++)
System.out.println("(" + i + ", " + j + ")");
}
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);
}
Or 要么
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.