当一行中输入了多个字符串时,程序会额外打印一次“输入字符串”。例如,我输入“一二”它提示“输入字符串”2 次。如果我输入“一二三”,它会提示“输入字符串”3 次,依此类推。有没有办法在不在循环中创建新对象的情况下解决这个问题?
import java.util.Scanner;
class Array {
public static void main(String[] args) {
String[] x = new String[1000];
Scanner kb = new Scanner(System.in);
int i = 0;
while (true) {
System.out.println ("Enter Strings");
x[i] = kb.next();
if (x[i].equals("done"))
break;
i++;
}
for (i = i - 1; i >= 0; i--) { //prints strings in reverse order prior to done
System.out.println(x[i]);
}
}
}
/*Example Output:
Enter Strings
One Two
Enter Strings
Enter Strings
Hello
Enter Strings
Bye
Enter Strings
done
Bye
Hello
Two
One*/