简体   繁体   English

Quick Java String / toString在每一行上打印一个char

[英]Quick Java String/toString Printing one char on each line

I need to take a String, and print each character of it on a seperate line. 我需要一个字符串,并在一个单独的行上打印它的每个字符。

I would use a for loop right? 我会使用for循环吗?

    public String toString(){
    for (int count=0; count < password.length(); count++)
    {
        System.out.print(password.charAt(count));
        System.out.print("\n");

    }
    return password; // I am confused on this. I don't want it to 
                       //return anything, really but I cannot make return type void



}

Is what I have, but I keep getting NullPointExceptions. 是我的,但我一直得到NullPointExceptions。 I have a method above that stores the password from the input, and the variable is defined in the class. 我有一个上面的方法存储输入的密码,变量在类中定义。 So, I figured it would pull it from that. 所以,我认为它会从中拉出来。

My Question is: How would I take a string and print each character from it, one on each line? 我的问题是:如何从字符串中打印每个字符,每行一个?

This would do the job: 这可以做到这一点:

String s = "someString";
for (int i = 0; i < s.length(); i++) {
    System.out.println(s.charAt(i));
}

First of all, "toString" is a bad choice for a function name because it's one of the standard methods available on every object. 首先,“toString”是函数名称的错误选择,因为它是每个对象上可用的标准方法之一。 That's why its a compile error to make its return type "void". 这就是为什么它的编译错误使其返回类型为“void”。 As for printing one char on every line: 至于在每一行打印一个字符:

public void printStringChars(String password) {
    if(password == null) {
        return;
    }

    for (int count=0; count < password.length(); count++) {  
        System.out.println(password.charAt(count));
    }

} }

If you don't want to return anything, you really shouldn't be overriding the toString() method. 如果你不想返回任何东西,你真的不应该重写toString()方法。 You should probably have a separate method such as: 您可能应该有一个单独的方法,例如:

public void printToConsole() {
    for (int count=0; count < password.length(); count++) {
         System.out.println(password.charAt(count));
    }
}

However, that's not the cause of your problem - I suspect the cause is that password is null. 但是,这不是问题的原因 - 我怀疑原因是password为空。 But you haven't shown us where you're trying to get that from... 但你没有告诉我们你在哪里尝试从...

No, you don't need a for loop. 不,你不需要for循环。 :) :)

one line code could achieve your goal: 一行代码可以实现您的目标:

System.out.println(yourString.replaceAll(".", "$0\n"));

You also can do this 你也可以这样做

import java.util.Scanner;

class que22 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("enter here your string");

        String a;

        a = input.nextLine();

        for (int i = 0;i < a.length(); i++ ) {
            System.out.println(a.charAt(i));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM