检查文本区域的内容是否为空(java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13448067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:46:07  来源:igfitidea点击:

Check if the content of text area is empty (java)

java

提问by user1748910

I am trying to read data from a textarea (JTextArea)and store the contents into a table(MySQL). I don't want the INSERTquery to execute if the textarea is empty or has a newline without any text. I tried the following code but it does not work. Could someone help me out. Thanks.

我正在尝试从 a 读取数据textarea (JTextArea)并将内容存储到table(MySQL). INSERT如果 textarea 为空或有一个没有任何文本的换行符,我不希望执行查询。我尝试了以下代码,但它不起作用。有人可以帮我吗。谢谢。

String data=todo_area.getText();//read contents of text area into 'data'
String newline = System.getProperty("line.separator");
boolean hasNewline = data.contains(newline);

if (data == null || !data.trim().equals("")||hasNewline==false)
{
    //INSERT  query
}

回答by Rasel

String data=todo_area.getText().trim(); //read contents of text area into 'data'
  if(!data.equals("")) {
     // code
    }

回答by user1835172

For me it's enough using this condition:

对我来说,使用这个条件就足够了:

if ((data.trim().length() > 0) && (!hasNewline)){
    //do the insert
}

data.trim().length() > 0is enough to make sure that the input is not null.

data.trim().length() > 0足以确保输入不为空。

回答by Abubakkar

Try using this condition for you check:

尝试使用此条件进行检查:

if ((data != null) && (data.trim().length() > 0 )  && (!hasNewline)){
//do the insert
}