2014-12-30 5 views
0

Я закодировал просто программу списка, которая добавляет текст, который пользователь вводит через JInputDialog (например: «go shop shop shop») в JList. Программа работает нормально, но я думал, что я хотел бы попытаться помешать пользователю нажать хорошо в диалоговом окне без ввода текста, или просто введя пробелы, через следующий код:Удаление пустых элементов из JList

 //if create button is pressed 
    }else if(src == create){ 
     //show an input dialog box 
     String s = JOptionPane.showInputDialog(this, "What do you want to remember?"); 

     /*f the length of the given string is zero, or if the length of the string without spaces 
     is zero, then tell the user*/ 
      if(s.length() == 0 || removeSpaces(s).length() == 0){ 
       System.out.println("Nothing has been entered"); 
       JOptionPane.showMessageDialog(this, "You must enter a text value!"); 

      //if the string is valid, add it to the file 
      }else{ 
       sfile.add(s); 
       System.out.println("Item added to list. " + s.length()); 
      } 

     }else if(src == close){ 
      System.exit(0); 
     } 
} 

    //remove all white spaces and tabs from the string 
    public String removeSpaces(String s){ 
     s.replaceAll("\\s+", ""); 
     return s; 
    } 
} 

Этот код работает и показывает Диалог «Ничего не введен», когда пользователь ничего не ввел, но не работает, когда пользователь вводит пробелы. Что я делаю не так?

+0

Что об использовании s.trim(), чтобы удалить пустое пространство вместо этого? –

+2

's.replaceAll (" \\ s + "," ");' не влияет на 's', поскольку строки неизменяемы, но возвращает новую строку. – Pshemo

ответ

1

Почему бы не использовать s.trim() вместо метода removeSpaces?

} else if (src == create) { 
    //show an input dialog box 
    String s = JOptionPane.showInputDialog(this, "What do you want to remember?"); 

    /*f the length of the given string is zero, or if the length of the string without spaces 
     is zero, then tell the user*/ 
    if (s.trim.length() == 0) { 
     System.out.println("Nothing has been entered"); 
     JOptionPane.showMessageDialog(this, "You must enter a text value!"); 
     //if the string is valid, add it to the file 
    } else { 
     sfile.add(s); 
     System.out.println("Item added to list. " + s.length()); 
    } 

} else if (src == close) { 
    System.exit(0); 
} 

или вы могли бы изменить способ удалить пробелы в: (как указано Pshemo)

public String removeSpaces(String s){ 
    return s.replaceAll("\\s+", ""); 
} 
Смежные вопросы