0

我是初学者,java我想寻求一些帮助。

编写一个名为 vertical 的方法,该方法接受一个字符串作为其参数,并将字符串的每个字母打印在不同的行上。例如,调用 vertical("hey now") 应该产生以下输出:

h
e
y

n
o
w

这就是我所做的。

public void vertical(String x){
    char OneByOne='x';
        for(int i=0;i<=x.length()-1;i++){
            OneByOne=x.charAt(i);
        }
        System.out.print(OneByOne);
}

当我要求它时,它给了我 w。但我很困惑。我创建了一个字符容器并调用位置 0。然后循环遍历它。位置 0 不应该从 h 开始。而不是给我 aw?

另外,我应该使用public void vertical(String x){ or public static void vertical(String x){吗?他们给我相同的输出。我去研究静态,他们告诉我静态意味着单一。那是什么意思?

4

6 回答 6

2
public void vertical(String x){
    int count = x.length();
    for(int i=0;i<count;i++){
       System.out.println(x.charAt(i));
    }      
}
于 2013-04-18T11:41:04.617 回答
1

I used a more conventional style here:

public void vertical(String x){
    for(int i = 0; i < x.length(); i++){
        char oneByOne = x.charAt(i);
        System.out.println(oneByOne);
    }
}

Less than length, i.o. less-equals length - 1.

Local declaration. Vars starting with small letter.

The rest is fine. charAt(i) gives the i'th char, just as conceived.

于 2013-04-18T11:45:26.503 回答
1

您需要在每次迭代中打印 char 。

public void vertical(String x){
    char OneByOne='x';
        for(int i=0;i<=x.length()-1;i++){
            System.out.println(x.charAt(i));
        }

}
于 2013-04-18T11:41:02.460 回答
1

您没有在循环内打印。另外,使用 println。

于 2013-04-18T11:37:25.323 回答
1

除了其他答案:您还可以使用 for each 循环:

public static void vertical(String x) {
    for (char OneByOne : x.toCharArray()) {
        System.out.println(OneByOne);
    }
}
于 2013-04-18T11:44:59.443 回答
0

您应该使用 prinln 而不是 print

System.out.println(OneByOne);

static关键字意味着您可以在没有类实例的情况下调用此方法。

于 2013-04-18T11:39:41.787 回答