我怎样才能打印具有特定字符的2D数组中的元素?

时间:2018-02-12 03:33:03

标签: arrays multidimensional-array char

我试图只打印第0行中有M的那些。我尝试过使用两个for循环,它只是打印所有这两个或者打印所有它们一次。我永远不能只获得MD MA ME等。

String [][] geo = {{"MD","NY","NJ","MA","ME","CA","MI","OR",},
            {"Detroit","Newark","Boston","Seattle"}};

        for (int j = 0; j < geo[0].length; j++)
        {
            if (geo[0][j].charAt(0) == 'M');
            System.out.println(geo[0][j]);
        }
    }

3 个答案:

答案 0 :(得分:1)

public static void main (String[] args) throws java.lang.Exception { String [][] geo = {{"MD","NY","NJ","MA","ME","CA","MI","OR",}, {"Detroit","Newark","Boston","Seattle"}}; for (int j = 0; j < geo[0].length; j++) { if (geo[0][j].charAt(0) == 'M'){ System.out.println(geo[0][j]); } } } 语句后面有一个分号,因此if语句实际上并不在其中。如果没有分号,它会起作用,但是你应该习惯使用大括号将行包裹在System.out.println语句中,即使只有一行。

删除了分号,它可以正常工作,但如果你向if添加另一个语句

,则很容易出错
if

这是明确无误的:

String [][] geo = {{"MD","NY","NJ","MA","ME","CA","MI","OR",},
        {"Detroit","Newark","Boston","Seattle"}};

    for (int j = 0; j < geo[0].length; j++)
    {
        if (geo[0][j].charAt(0) == 'M')
            System.out.println(geo[0][j]);
    }
}

答案 1 :(得分:0)

if块代码为null,因为在它的末尾有一个分号。尝试删除它或使用括号括起print语句。

if (geo[0][j].charAt(0) == 'M')
{
        System.out.println(geo[0][j])
}

答案 2 :(得分:0)

所以我观察了代码,问题似乎与if语句有关......这是工作代码:

library(scales)

ggplot(SNPs, aes(genotype))
    genocount + geom_bar(aes(position = "fill", fill = chromosome))+
    geom_text(aes(label = percent(chromosome/sum(chromosome))))
    scale_y_continuous(labels = percent_format())