更新时间:2023-11-06 18:08:04
用户伊朗的权利.无论如何,您的程序有点不干净.我建议您摆脱注释,并使用变量名告诉读者它们应该包含的内容.您想要的可能是这样:
User Eran ist right. Your program is a bit unclean anyway. I suggest you get rid of the comments and use variable names which tell the reader what they are supposed to contain. What you want is probably this:
import java.util.Scanner;
public class Pr8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you wish to enter? ");
while (!scanner.hasNextInt()) {
System.err.print("Again, how many numbers? ");
scanner.next();
}
int numberCount = scanner.nextInt();
int[] numbers = new int[numberCount];
for (int i = 0; i < numberCount; i++) {
String numberString;
System.out.print("Please enter string #" + (i + 1) + " containing a number: ");
scanner.nextLine();
while ((numberString = scanner.findInLine("[+-]?[0-9]+")) == null) {
System.err.print("Again, string #" + (i + 1) + " should contain a number: ");
scanner.nextLine();
}
numbers[i] = Integer.parseInt(numberString);
System.out.println("Number #" + (i + 1) + " found = " + numbers[i]);
}
}
}
示例控制台日志:
How many numbers do you wish to enter? weewdfsa
Again, how many numbers? 324klj
Again, how many numbers? 5
Please enter string #1 containing a number: 23
Number #1 found = 23
Please enter string #2 containing a number: sdfsdf
Again, string #2 should contain a number: werq
Again, string #2 should contain a number: sdf345df
Number #2 found = 345
Please enter string #3 containing a number: -34ewr
Number #3 found = -34
Please enter string #4 containing a number: wqweq+555
Number #4 found = 555
Please enter string #5 containing a number: xxx-11yyy
Number #5 found = -11