我正在我的教科书中练习练习,将整数(负数和正数)添加到数组中。我希望用户能够在数据到达结束之前终止输入数字[50]。
这就是我想出来的:
用户输入存储在字符串中的数字。如果keepLooping为true且index<阵列的大小;它将通过标记解析字符串并将数字放入int数组。
必须有一种更简单的方法来做到这一点,我无法让我的代码正常工作,我们将非常感谢任何帮助:
// Create Objects to use in program
Scanner keyboard = new Scanner(System.in);
int[] arrayOfNumbers = new int[50];
// Prompt for input
System.out.println("Enter upto 50 integers separated by a space.");
System.out.println("Type x to signal no more integers to enter.");
int index = 0;
boolean keepLooping = true;
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
keepLooping = false;
}
if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
}
// DEBUG, Print Array
for (int k=0; k < arrayOfNumbers.length; k++) {
System.out.println(arrayOfNumbers[k]);
}
答案 0 :(得分:2)
如果您逐步调试程序(例如,在Eclipse中使用 F6 步进),您会注意到index
的值不会改变。最快的解决方法是:
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
keepLooping = false;
}
if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
index++;
}
<小时/> 但当然,这只解决了数组填充问题。接下来是编程关注的良好实践,其余答案将全面介绍。
答案 1 :(得分:2)
您可以使用for
循环简化一点,并在循环中退出break
:
for (int index = 0; index < arrayOfNumbers.length; ++index) {
String numToAdd = keyboard.nextLine();
if (numToAdd.equals("x") || numToAdd.equals("X")) {
break;
}
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
答案 2 :(得分:0)
int index = 0;
boolean keepLooping = true;
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if (numToAdd.equalsIgnoreCase("x")) { // Use EqualsIgnoreCase to shorten it
keepLooping = false;
} else { // Use an else statement instead of evaluating the inverse
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
index++; // Increment the index to avoid eternal loop and actually fill the array
}