aspose file tools*
The moose likes Java in General and the fly likes Using .equals in a while statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using .equals in a while statement" Watch "Using .equals in a while statement" New topic

Using .equals in a while statement

Rory Rezzelle

Joined: Sep 30, 2003
Posts: 5
Hi all, I'm new here, but I need to know this ASAP.
I making a proggy that allows the user to input a product then how much it is. When the user doesn't input a product, Java displays the average amount of all the prices.
My prolem comes in when I use ".equals". Here's what I got:
import javax.swing.*;
import java.text.NumberFormat; //class for numeric formatting
import java.util.Locale;//class for country-specific information
public class Homework5{
public static void main( String args[] )
String prod_name;
String prod_price;
int price;
int tot_price = 0;
int prod_number = 1;
int avg_price;
// create NumberFormat for currency in US dollar format
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance ( Locale.US );
// create JTextArea to display Output
JTextArea outputTextArea = new JTextArea();
// set first line of text in outputTextArea
outputTextArea.setText( "Name\tPrice\n" );
prod_name = JOptionPane.showInputDialog( "Enter product name:" );
while (prod_name.equals(""))
prod_price = JOptionPane.showInputDialog( "Enter product price:" );
price = Integer.parseInt( prod_price );
tot_price = price + tot_price;
outputTextArea.append( prod_name + "\t" + moneyFormat.format( prod_price ) + "\n" );
prod_name = JOptionPane.showInputDialog( "Enter product name:" );
avg_price = tot_price / prod_number;
outputTextArea.append ( "Average price =" + moneyFormat.format( avg_price ) );
System.exit ( 0 );
What happens is, when I type anything in for prod_name, I can't type in anything for prod_price because it reads prod_name as true when I type something in. When I say prod_name.equals("") then I'm asking for an empty string. How can I say "while (prod_name.equals( <any string> ) ?
Please help.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24187

Welcome to JavaRanch!
You want to do something if the String is not null and not empty, yes? So that's what you say

Note that "!" before the prod_name.equals(""), which means "not".

[Jess in Action][AskingGoodQuestions]
wood burning stoves
subject: Using .equals in a while statement