英文:
Trying to create a gridgenerator in java:
问题
package edu.skidmore.cs106.lab09.problem14;
import java.util.Random;
public class GridGenorator {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] gridArray = new String[6];
        gridArray[0] = "+";
        gridArray[1] = "-";
        gridArray[2] = "/";
        gridArray[3] = "\\";
        gridArray[4] = "|";
        gridArray[5] = "_";
        
        for (int elementx = 0; elementx < 7; elementx++) {
            for(int elementy = 0; elementy < 20; elementy++) {
                Random rand = new Random();
                int randomNum = rand.nextInt(6);
                System.out.print(gridArray[randomNum]);  // Use print instead of println
            }
            System.out.println();  // Move to a new line after printing each row
        }
    }
}
英文:
I'm trying to create a program as described in the image linked below. I'm finding trouble with how to print the characters on the same line so that I can get 20 across and how to go to a new line after the first 20 characters have printed. Can you help me figure out a way to print the randomly selected characters into a 20 by 7 grid? Thank you for the help! Below is what I have so far but it's printing every new character on its own line and for gridArray[3] the forward-slash has to have two quotes otherwise it says that it's not a valid string. Does anyone know how I could solve these problems?
package edu.skidmore.cs106.lab09.problem14;
import java.util.Random;
public class GridGenorator {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] gridArray = new String[6];
		gridArray[0] = "+";
		gridArray[1] = "-";
		gridArray[2] = "/";
		gridArray[3] = "\"";
		gridArray[4] = "|";
		gridArray[5] = "_";
		for (int elementx = 0; elementx < 7; elementx++) {
			for(int elementy = 0; elementy<20; elementy++) {
				Random rand = new Random();
				int randomNum = rand.nextInt(6);
				System.out.println(gridArray[randomNum]);
			}
		}
	}
}
答案1
得分: 0
`System.out.println`会打印一个新行,但并不是每次都需要这样做,只需要在每组20个之后,所以尝试使用以下代码:
for (int elementx = 0; elementx < 7; elementx++) {
    for(int elementy = 0; elementy < 20; elementy++) {
        Random rand = new Random();
        int randomNum = rand.nextInt(6);
        System.out.print(gridArray[randomNum]);
    }
    System.out.println();  // 现在您想要打印一个换行
}
英文:
System.out.println prints a new line which you do not want to do every time, only after a group of 20, so try
    for (int elementx = 0; elementx < 7; elementx++) {
        for(int elementy = 0; elementy<20; elementy++) {
            Random rand = new Random();
            int randomNum = rand.nextInt(6);
            System.out.print(gridArray[randomNum]);
        }
        System.out.println();  // now you want to print a newline
    }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论