I am trying to write an applet that receives 2 inputs from a user then opens a window and displays the 2 numbers that were input, along with a message of either "the numbers are equal", or "this number is the largest".

My problem--my program never returns "the numbers are equal". If I put in equal numbers like 76 and 76 it returns "76 is the largest number". Why?

here is my code

import java.awt.Graphics;//program uses class Graphics
import javax.swing.JApplet;//program uses class JApplet
import javax.swing.JOptionPane;//program uses class JOptionPane
import java.math.*;//program uses math.max

public class LargerApplet extends JApplet
	//variables to be used

	String firstNumber;
	String secondNumber;
	String result;

	private double answer;// finds max entered by user

		//initialize applet by obtaining values from user

		public void init()

			double number1;//first number to  evaluate
			double number2;//second number to evaluate

			//obtain first number from user
			firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" );

			//obtain second number from user
			secondNumber = JOptionPane.showInputDialog( "Enter second floating-point value" );

			//convert numbers from type String to type double
			number1 = Double.parseDouble( firstNumber );
			number2 = Double.parseDouble( secondNumber );

			answer = Math.max( number1, number2);

		}//end method init

		//draw results in a rectangle on applet's background
		public void paint( Graphics g )
			super.paint( g );//call superclass version of method paint

			//draw rectangle starting from (15, 10) that is 270
			//pixels wide and 20 pixels tall
			g.drawRect( 15, 10, 270, 50 );

			//draw results as a String at ( 25, 25 )
			g.drawString( "Your first number was--              " + firstNumber, 25,25 );
			g.drawString( "Your second number  was--      " + secondNumber ,25,35 );

			if ( firstNumber == secondNumber )
				g.drawString ( "--Your numbers are equal--", 25,45 );

			}//end if


					g.drawString ( answer + "--Is the larger number--", 25, 55 );

				}//end else

		}//end method paint

	}//end class IsLargerApplet
7 Years
Discussion Span
Last Post by tmoney7566

firstNumber and secondNumber are Strings (I am pretty sure you know this). since they are strings, == will only evaluate true if they are the same object. you want to use .equals to compare Strings in the way you intend.

Thank you for the help.

That was it.
if (firstNumber.equals(secondNumber)) worked great. Thank you

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.