问题
I've been trying to repeat this program, but when I do, I keep getting errors. I repeated it before, but it asked to repeat after every row of asterisks. This is what I have so far:
import java.util.Scanner;
public class Pyramid
{
//Displaying a Pyramid
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
//Get user input = number of rows to print in a pyramid
System.out.print("Enter an integer for the number of rows: ");
int userInput = scanner.nextInt();
scanner.close();
int myLevel;
int i, j , k;
myLevel = userInput;
for (i = 1; i <= myLevel; i++) {
for (k =1; k <= myLevel-i; k++)
System.out.print(" ");
for (j = k+1; j <=myLevel; j++)
System.out.print( "*");
for(int l=myLevel;l>k-1;l--)
System.out.print( "*");
System.out.println("");
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
}
}
回答1:
I am guessing that you want to repeat the above logic - right?
If this is the case then do not close your scanner
Also your while is wrongly formatted.
while("Y".equalsIgnoreCase(scanner.next().trim()));
Having the ;
on the end will cause an endless loop in this case.
try
private static void myMethod(Scanner scanner) {
//Get user input = number of rows to print in a pyramid
System.out.print("Enter an integer for the number of rows: ");
int userInput = scanner.nextInt();
int myLevel;
int i, j , k;
myLevel = userInput;
for (i = 1; i <= myLevel; i++) {
for (k =1; k <= myLevel-i; k++)
System.out.print(" ");
for (j = k+1; j <=myLevel; j++)
System.out.print( "*");
for(int l=myLevel;l>k-1;l--)
System.out.print( "*");
System.out.println("");
}
and
call it like
Scanner scanner = new Scanner(System.in);
do {
myMethod (scanner);
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
scanner.close ();
回答2:
You have an empty while statement at the end of code. You're trying to read input that doesn't exist. You need to encapsulate the entire program in a loop. You don't need to loop until there is input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do{
//Get user input = number of rows to print in a pyramid
System.out.print("Enter an integer for the number of rows: ");
int userInput = scanner.nextInt();
int myLevel;
int i, j , k;
myLevel = userInput;
for (i = 1; i <= myLevel; i++) {
for (k =1; k <= myLevel-i; k++)
System.out.print(" ");
for (j = k+1; j <=myLevel; j++)
System.out.print( "*");
for(int l=myLevel;l>k-1;l--)
System.out.print( "*");
System.out.println("");
}
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
}
You also close the scanner, so you can't re-use it.
来源:https://stackoverflow.com/questions/25276548/repeating-a-program-in-java