user1176922
user1176922

Reputation: 93

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?

    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. 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?

Upvotes: 3

Views: 74991

Answers (5)

Abdihakiim yusuf Adan
Abdihakiim yusuf Adan

Reputation: 11

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));
        }
    }
}

Upvotes: 0

Kent
Kent

Reputation: 195229

No, you don't need a for loop. :)

one line code could achieve your goal:

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503050

If you don't want to return anything, you really shouldn't be overriding the toString() method. 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. But you haven't shown us where you're trying to get that from...

Upvotes: 2

eternaln00b
eternaln00b

Reputation: 1053

First of all, "toString" is a bad choice for a function name because it's one of the standard methods available on every object. That's why its a compile error to make its return type "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));
    }

}

Upvotes: 4

mtsz
mtsz

Reputation: 2855

This would do the job:

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

Upvotes: 8

Related Questions