Home > Back-end >  User input a word then print letters of the word on a new line for java
User input a word then print letters of the word on a new line for java

Time:12-11

I need help using just String method, indexOf, substring, accumulators, while loops. I want the user to input a word using JOptionPane.showInputDialog and will display each letter of word on a new line in the output. How do you do this in java?

Ex.

Input: Dog

Output:

D
o
g

Here's my code so far (it really needs correcting):

import javax.swing.*;
public class Exercise_28 {
    public static void main(String[] args) {
        String input;
        String letters;
        int num1;
        int num2;

        input = JOptionPane.showInputDialog("Enter a word: ");
        num1 = input.length() - 1;
        num2 = input.length() - num1 - 1;
        letters = input.substring(0, 1);

        while (num2 <= num1) {
            System.out.println(letters);
            num2  ;
            letters = input.substring(num2, num2   1);
        }
        System.exit(0);
    }
}

CodePudding user response:

import javax.swing.*;
public class Exercise28 {
    public static void main(String[] args) {
        String input;
        input = JOptionPane.showInputDialog("Enter a word: ");
        int i =0;

        //Solution1. input as array using chatAt(index)
        while(i< input.length())
        {
            System.out.println(input.charAt(i));
            i  ;
        }

        //Solution2. Get a substring beginning at index and take 1 character. Remember endIndex is exclusive. Example substring(3, 4) take character at index = 3 to index = 4(exclusive), total 1 character,
        i=0;
        while(i< input.length())
        {
            System.out.println(input.substring(i, i 1));
            i  ;
        }
    }
}

CodePudding user response:

You can change your code like that

 import javax.swing.*;
public class Exercise_28 {
    public static void main(String[] args) {
        String input;
        String letters;
        int num1;
        int num2;

        input = JOptionPane.showInputDialog("Enter a word: ");
        num1 = input.length() - 1;
        num2 = input.length() - num1 - 1;
           //  letters = input.substring(0, 1);

    while (num2 <= num1) {
        letters = input.substring(num2, num2   1);
        System.out.println(letters);
        num2  ;
    }
    System.exit(0);
    }
}

error occurs when you want substring input without checking your num2 with while

  • Related