Search code examples
javaswinginputjoptionpane

Input won't trim


Brand new to this but I'm not sure what I am doing wrong as the output will not trim.

package cs520.hw3.part1;

import javax.swing.JOptionPane;

public class StringTest {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
        //String delimiter = ",";
        //String[] tokens = input.split(delimiter);
        System.out.println(input.trim());
    }
}

Solution

  • There is a difference between removing the leading & trailing spaces (using trim() and replacing all spaces from a String (using replaceAll(" ", ""))

    Example output

    ' Andrew,      52,  Sydney         '
    'Andrew,      52,  Sydney'
    'Andrew,52,Sydney'
    
    1. Raw String
    2. trim()
    3. replaceAll(" ", "")

    Code

    import javax.swing.*;
    
    public class TrimSpace {
        
        TrimSpace() {
            String s = JOptionPane.showInputDialog(null, 
                    "Name, Age, City", 
                    "Person Details", 
                    JOptionPane.QUESTION_MESSAGE);
            // show the raw string entered by user
            System.out.println(String.format("'%1s'", s));
            // remove leading & trailing space from string
            System.out.println(String.format("'%1s'", s.trim()));
            // remove all spaces from string
            System.out.println(String.format("'%1s'", s.replaceAll(" ", "")));
        }
        
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    new TrimSpace();
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }