对于一个类项目,我必须编写一个代码,打印一个由用户指定长度的星号组成的框。我们必须制作两种类型的盒子;基本和对角线。基本的盒子只是一个由星号组成的普通盒子,我已经制作过了。对角线框内部必须有一条对角线,看起来像这样: http://prntscr.com/3fbbot
这是我到目前为止的代码:
public static void main(String[] args) {
Scanner type = new Scanner(System.in);
Scanner number = new Scanner(System.in);
Boolean f = true;
while (f) {
System.out.print("Enter a box type, basic or diagonal: ");
String g = type.nextLine();
if (g.equals("basic") || g.equals("diagonal")) {
}
else {
continue;
}
System.out.print("Enter a number between 2 - 16: ");
try {
int boxSize = number.nextInt();
if (g.equals("basic")) {
if (boxSize >= 2 && boxSize <= 16) {
for (int i = 0; i < boxSize * boxSize;i++) {
int row = i / boxSize;
int col = i % boxSize;
if (row == 0 && col < boxSize-1) {
System.out.print("*");
}
else if (col == 0) {
System.out.print("*");
}
else if (col == (boxSize -1)) {
System.out.println("*");
}
else if (row == (boxSize - 1)) {
System.out.print("*");
}
else {
System.out.print(" ");
}
}
}
else {
System.out.println("Please use a proper integer.");
}
System.out.print("Make another square? Type yes or no: ");
Scanner answer = new Scanner(System.in);
if (answer.nextLine().equals("no")) {
System.out.print("Thanks for playing!");
System.exit(0);
}
}
else {
}
}
catch(Exception e){
System.out.println("RESETTING. Please type an integer this time.");
}
}
}
如果您需要我更具体或需要更多细节,请询问。提前谢谢。
答案 0 :(得分:0)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a box type, basic or diagonal: ");
String g = input.nextLine();
if (!(g.equals("basic") || g.equals("diagonal"))) {
continue;
}
System.out.print("Enter a number between 2 - 16: ");
try {
int boxSize = Integer.parseInt(input.nextLine());
if (boxSize >= 2 && boxSize <= 16) {
for (int i = 0; i <boxSize; i++) {
for (int j = 0; j < boxSize; j++) {
if (i == j && g.equals("diagonal")) {
System.out.print("*");
} else if (i == 0 || i == boxSize-1) {
System.out.print("*");
} else if (j == 0 || j == boxSize-1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
} catch(Exception e){
System.out.println("RESETTING. Please type an integer this time.");
}
System.out.print("Make another square? Type yes or no: ");
if (input.nextLine().equals("no")) {
System.out.print("Thanks for playing!");
System.exit(0);
}
}
}
答案 1 :(得分:0)
Short and sweet answer could be:
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the square: ");
int n = input.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i>1 && i<n && j>1 && j<n){
if(i==j){
System.out.print(" * ");
}else{
System.out.print(" ");
}
} else{
System.out.print(" * ");
}
}
System.out.println();
}
Let me know if somebody else need more help on this. Thank you.