我有一个方法可以打印出非空的String数组元素。期望的输出:
1. cook
2. chef
3. baker
4. butcher
5. distiller
输出获取:
1. cook
3. chef
4. baker
7. butcher
9. distiller
这些数字并不像第一个例子中那样连续。显然这是因为当'i'不为空时它只打印'i'。无论如何我可以让它看起来像第一个例子?我尝试了不同的解决方案,但似乎都没有。
public class Main {
public void testMethod() {
String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null)
System.out.println((i + 1) + ". " + myArray[i]);
}
}
public static void main(String[] args) {
Main main = new Main();
main.testMethod();
}
}
答案 0 :(得分:4)
只需保留一个柜台:
public void testMethod() {
String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
int j = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null) {
System.out.println(++j + ". " + myArray[i]);
}
}
}
答案 1 :(得分:1)
由于您无法使用i
作为计数器,因此您需要一个单独的计数器:
public void testMethod() {
String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
int counter = 1;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null)
System.out.println((counter++) + ". " + myArray[i]);
}
}
答案 2 :(得分:0)
是的,只需记下您打印的数量,而不仅仅是指数:
- (void)willPresentSearchController:(UISearchController *)searchController {
searchController.searchBar.tintColor = [UIColor whiteColor];
}
答案 3 :(得分:0)
您需要一个新的整数变量来进行计数。 试试这个 -
public class Main {
public void testMethod() {
int iter = 1;
String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null) {
System.out.println((iter++) + ". " + myArray[i]);
}
}
}
public static void main(String[] args) {
Main main = new Main();
main.testMethod();
}
}
答案 4 :(得分:0)
为count
non-null values
变量
public void testMethod() {
String myArray[] = new String[] { "cook", null, "chef", "baker", null,
null, "butcher", null, "distiller" };
int j=0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null){
System.out.println((j + 1) + ". " + myArray[i]);
j++;
}
}
}
<强>输出强>
1. cook
2. chef
3. baker
4. butcher
5. distiller
答案 5 :(得分:0)
请试一试。
public class Main {
public void testMethod() {
String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
int count = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] != null)
System.out.println(((count++) + 1) + ". " + myArray[i]);
}
}
public static void main(String[] args) {
Main main = new Main();
main.testMethod();
}
}