?
Solved

Java Nested IF statement

Posted on 2011-10-23
28
Medium Priority
?
222 Views
Last Modified: 2012-05-12
I am trying to create a Nested IF statment

example

If (button pressed)
 If (search txt field is blank)
print "enter search query"
break;
else
do search

For some reason my txt1 (JTextField) is not null it has a huge string in it comprising of what looks like the gui's settings. (code on lines 55 -56 do printlns)

My code attached is meant to create a new string (txtCheck) which is null it then compares or if == to txt1 but as mentioned above its not null.
Can anyone explain why its not null if it does not have anythign typed into it? and maybe how I can do this check?



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	
	public void actionPerformed(ActionEvent event)
	{
	
	
		if (event.getSource().equals(btn1)){
			String txtCheck = txt1.getText(); 
			System.out.println(txt1);
          System.out.println(txtCheck);
			if(txt1.equals(txtCheck)){
				System.out.println("Enter Query String");
				
			}
			
			String searchString = txt1.getText();
            Search SearchObject = new Search();
         
            try{
            SearchObject.searchGoog(searchString);
            txtArea.setText(SearchObject.getLine());
            }catch(Exception ex){
                ex.printStackTrace();
            }}
		
		}
	
	public static void main (String[] args)
	{
	new Main();
	}
}

Open in new window

import java.io.*;
import java.net.*;


public class Search {
public String line;
    
    public void searchGoog(String searchString) throws IOException {
        
	URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + searchString);
	URLConnection connection = url.openConnection();
        
	StringBuilder builder = new StringBuilder();
	BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String buff = null;
	while((buff = reader.readLine()) != null) {
	builder.append(buff);
        
	}
	
System.out.println(builder.toString());
        line = builder.toString();

    }
 public String getLine() {
        return line;
    
    }

    public void setLine(String line) {
        this.line = line; 
    }    
}

Open in new window

0
Comment
Question by:k3eper
  • 12
  • 9
  • 7
28 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37014252


if(txt1.equals(txtCheck)){


txt1 is JTExtFiled
txtCheck is a String


They will never be equal - diffferent types
0
 

Author Comment

by:k3eper
ID: 37014253
Arr i did wonder about that, so how do i check if the txt field has anything typed into it?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014254
the way you should heck for no input is

if(txt1.getText().trim().length() == 0){

// no input given - report error
}
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 37014258
You're printing the text components' internal state by doing that. Why are you doing that?
0
 

Author Comment

by:k3eper
ID: 37014263
arr maybe create another textfield and compare them?
0
 

Author Comment

by:k3eper
ID: 37014267
no that wouldnt work  lol (should think befor posting really)
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014269
or of course you can do it like that:

String txtCheck = txt1.getText();
if(txtCheck.trim().length() == 0) {...}

This is the same thing
0
 

Author Comment

by:k3eper
ID: 37014270
arr check on length

thanks ill try that quick
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014271
the good practice is to use this trim() method - this will cause message to print even if yuser
pust a coulpe of spaces there inadvertently
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37014277
You should do it this way or you will probably have to call the method again to trim it, which is inefficient
String txtCheck = txt1.getText().trim(); 
if(txtCheck.length() == 0) {...}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014285
Where to call trim() - those are real details depending on what you do next with it.
Anyway, trim() will take no time
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37014300
>>Anyway, trim() will take no time

Everything takes time - unless you've got a very special machine
0
 

Author Comment

by:k3eper
ID: 37014308
this look correct?

Im not getting any output to the txtArea.
if (event.getSource().equals(btn1)){
   if(txt1.getText().trim().length()==0){
   txtArea.setText("Enter search query");}
........}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014310
No, you should think about the performance only when doing crucial bottleneck operations - those are very rare
otherwise it is just waste of your mental resources - you ca do thousands of trim's in the time you'll make connection to
your web page - so don't spend your time thinking about such things.
In a few cases in your priogramming life you'll encounter indee bottleneck situations - then think about those cases
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014313
looks correct to me
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37014345
>>otherwise it is just waste of your mental resources

That's just nonsense i'm afraid and just results in the sort of poor quality code i frequently see here
0
 

Author Comment

by:k3eper
ID: 37014350
Im all for best practise so will follow that when possible ( would rather learn the correct way now than try break bad habbits).

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37014353
>>Im all for best practise so will follow that when possible

That's good. Certainly don't let anyone put you off doing so
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014359
the correct way is to think of what is relevant in each particular case - that will be the most effective way
0
 

Author Comment

by:k3eper
ID: 37014440
any idea why i cant seem to get the "Enter query string" into the txtArea?


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	
	public void actionPerformed(ActionEvent event)
	{
	
	
		if (event.getSource().equals(btn1)){
			if(txt1.getText().trim().length()==0){
				String txtCheck = "Enter Query String";
				txtArea.setText(txtCheck);}
			
		String searchString = txt1.getText();
        Search SearchObject = new Search();
         
        try{
            SearchObject.searchGoog(searchString);
            txtArea.setText(SearchObject.getLine());
            }catch(Exception ex){
                ex.printStackTrace();}
            }
		
	}
	
	public static void main (String[] args)
	{
	new Main();
	}
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014452
you should put return;
after stetText
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014456
like that:

  String searchString = txt1.getText();
            if(searchString.trim().length() == 0){

                System.out.println("yuyuy");
                txtArea.setText("enter query");
                return;
            }

Open in new window


otherwise - it is busy searching for youur stuuff no matter that there was no query
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 37014521
You can use the following. Avoid placing return in arbitrary places in methods - it just makes them hard to read and maintain:

public void actionPerformed(ActionEvent event) {
	if (event.getSource().equals(btn1)) {
	    String searchParam = txt1.getText().trim();
	    if (searchParam.length() < 1) {
		String txtCheck = "Enter Query String";
		txtArea.setText(txtCheck);
	    }

	    else {
		Search SearchObject = new Search();

		try {
		    SearchObject.searchGoog(searchParam);
		    txtArea.setText(SearchObject.getLine());
		} catch (Exception ex) {
		    ex.printStackTrace();
		}
	    }
	}
    }

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014545

Any  way is good to avoid going to search in this situation;
return is as good as anything else.

Actually, reading code with returns is much easier than with convoluted ifs.
0
 

Author Comment

by:k3eper
ID: 37014713
thanks CEHJ and for yan for all your help so far. Im sure ill hit another wall soon enough ^_^.

The learning material ive used hasnt shown anything like trim before.
0
 

Author Closing Comment

by:k3eper
ID: 37014714
Brilliant JAVA skills
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37014739
k3eper, look that's unfair - I was finding all the issues in this thread, CEHJ was then making some general remarks
You can believe in his remarks or not - that is philosophical difference, but the issues were pointed out in my postings
first in both cases.
This is very unfair
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37014977
k3eper, don't forget points splits are possible
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
The viewer will learn how to implement Singleton Design Pattern in Java.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month17 days, 9 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question