• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

Java Nested IF statement

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
k3eper
Asked:
k3eper
  • 12
  • 9
  • 7
1 Solution
 
for_yanCommented:


if(txt1.equals(txtCheck)){


txt1 is JTExtFiled
txtCheck is a String


They will never be equal - diffferent types
0
 
k3eperAuthor Commented:
Arr i did wonder about that, so how do i check if the txt field has anything typed into it?
0
 
for_yanCommented:
the way you should heck for no input is

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

// no input given - report error
}
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
CEHJCommented:
You're printing the text components' internal state by doing that. Why are you doing that?
0
 
k3eperAuthor Commented:
arr maybe create another textfield and compare them?
0
 
k3eperAuthor Commented:
no that wouldnt work  lol (should think befor posting really)
0
 
for_yanCommented:
or of course you can do it like that:

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

This is the same thing
0
 
k3eperAuthor Commented:
arr check on length

thanks ill try that quick
0
 
for_yanCommented:
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
 
CEHJCommented:
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
 
for_yanCommented:
Where to call trim() - those are real details depending on what you do next with it.
Anyway, trim() will take no time
0
 
CEHJCommented:
>>Anyway, trim() will take no time

Everything takes time - unless you've got a very special machine
0
 
k3eperAuthor Commented:
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
 
for_yanCommented:
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
 
for_yanCommented:
looks correct to me
0
 
CEHJCommented:
>>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
 
k3eperAuthor Commented:
Im all for best practise so will follow that when possible ( would rather learn the correct way now than try break bad habbits).

0
 
CEHJCommented:
>>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
 
for_yanCommented:
the correct way is to think of what is relevant in each particular case - that will be the most effective way
0
 
k3eperAuthor Commented:
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
 
for_yanCommented:
you should put return;
after stetText
0
 
for_yanCommented:
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
 
CEHJCommented:
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
 
for_yanCommented:

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
 
k3eperAuthor Commented:
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
 
k3eperAuthor Commented:
Brilliant JAVA skills
0
 
for_yanCommented:
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
 
CEHJCommented:
k3eper, don't forget points splits are possible
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 12
  • 9
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now