Java 使用嵌套环创建交替瓷砖地板
我试图创建一个程序,从用户的输入输出一个替代的瓷砖设计。即,如果使用输入3,结果将是3x3设计,如下所示:Java 使用嵌套环创建交替瓷砖地板,java,Java,我试图创建一个程序,从用户的输入输出一个替代的瓷砖设计。即,如果使用输入3,结果将是3x3设计,如下所示: |R|B|R| |B|R|B| |R|B|R| 我在为输出获取正确数量的磁贴时遇到问题。对于3的输入,第2行有一个额外的“| R |”,随后创建第4行。输出结果为: |R|B|R| |B|R|B|R| |R|B|R| |B 我在下面附上了我的代码。我知道这与: if (r%2 == 0){ System.out.println("|"); System.out.print("|B")
|R|B|R|
|B|R|B|
|R|B|R|
我在为输出获取正确数量的磁贴时遇到问题。对于3的输入,第2行有一个额外的“| R |”,随后创建第4行。输出结果为:
|R|B|R|
|B|R|B|R|
|R|B|R|
|B
我在下面附上了我的代码。我知道这与:
if (r%2 == 0){
System.out.println("|");
System.out.print("|B");
有什么想法吗
import java.util.*;
public class tileFloor {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println("Enter x:");
int x;
x = input.nextInt();
if (x < 10)
{ int c = 0;
int r = 0;
while (r < x ){
while (c < x ){
if (c %2 == 0 )
System.out.print("|R");
else if (c%2 != 0)
System.out.print("|B");
c++;
}//end 'while (c<x)' loop
if (r%2 == 0){
System.out.println("|");
System.out.print("|B");
}
else if (r%2 != 0)
System.out.println("|");
c = 0;
r++;
}//end 'while (r<x)' loop
}//end if statement
input.close();
}//end main
}//end class
import java.util.*;
公共级瓷砖地板{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入x:”);
int x;
x=input.nextInt();
if(x<10)
{int c=0;
int r=0;
while(r
import java.util.*;
class tileFloor {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println("Enter x:");
int x;
x = input.nextInt();
int count = 0;
if (x < 10)
{ int c = 0;
int r = 0;
while (r < x ){
if(r%2 == 0)
{
count = 0;
}
else
{
count = 1;
}
while (c < x ){
if (count %2 == 0)
{
System.out.print("|R");
}
else
{
System.out.print("|B");
}
count++;
c++;
}//end 'while (c<x)' loop
System.out.println("|");
c = 0;
r++;
}//end 'while (r<x)' loop
}//end if statement
input.close();
}//end main
}//end class
import java.util.*;
类瓷砖地板{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入x:”);
int x;
x=input.nextInt();
整数计数=0;
if(x<10)
{int c=0;
int r=0;
while(r }//结束’while(c这个解决方案怎么样?它的作用更加明确:
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Enter x: ");
int x = input.nextInt();
if (x < 10) {
int r = x;
int c;
while (r-- > 0) {
c = x;
while (c-- > 0) {
System.out.print("|" + ((c + r & 1) == 0 ? "R" : "B"));
}
System.out.println("|");
}
}
}
}
publicstaticvoidmain(字符串[]args){
try(扫描仪输入=新扫描仪(System.in)){
系统输出打印(“输入x:”;
int x=input.nextInt();
if(x<10){
int r=x;
INTC;
而(r-->0){
c=x;
而(c-->0){
系统输出打印(“|”+((c+r&1)=0?“r”:“B”);
}
System.out.println(“|”);
}
}
}
}
为什么不使用for循环而不是一段时间?既然你知道它应该迭代多少次?这听起来是个不错的主意,但我对它们不太满意。虽然循环很危险,因为一个简单的错误可能意味着它们永远不会退出。for循环发生的可能性要小得多。我会记住这一点下次我处理循环时请注意。谢谢你的关心。奇数输入时这很好,但偶数输入时不会交替。非常好!谢谢你的帮助Vishal!:DOkay,OP没有真正提到他期望的结果…但现在我猜这有点像一个棋场…我更正了我的答案!De有限清洁,但如上所述,我有麻烦的for循环。谢谢你的回应,虽然!