8-7. Modify exercise 7-2 on comparing strings so it is now done in an applet ins
ID: 3851172 • Letter: 8
Question
8-7. Modify exercise 7-2 on comparing strings so it is now done in an applet instead of an application. The prompts will now be in labels and the input will now be textfields. The user will hit enter in the secondtextfield to get the results in two other answer labels. The results (which is greater and the difference amount) will be in these two other answer labels. Declare everything at the top, use the init to add the components to your container (use background and foreground colors and the flow layout), and use actionPerformed to do three things: get the text out of the textfields for the two strings (instead of readLines), to perform the nested if else with the comparisons, and the setting of the answers in the two answer labels - which is greater and the difference (instead of printlns).
Here is the original code for 7-2:
Explanation / Answer
The required code is given as follows. Hope it will help you understand the code made.
cmp2str.java
import java.awt.*;
import java.applet.*;
public class cmp2str extends Applet
{
TextField tf,tf1;
public void init()
{
tf = new TextField(10);
tf1 = new TextField(10);
add(tf);
add(tf1);
tf.setText("");
tf1.setText("");
}
public void paint(Graphics g)
{
String ip1,ip2;
g.drawString("Plese enter strings for comparison: ",15,55);
ip1=tf.getText();
ip2=tf1.getText();
g.setColor(Color.black);
if(ip1.equals(ip2))
{
g.drawString(ip1+"is equal to"+ip2,15,75);
}
else if(ip1.equalsIgnoreCase(ip2))
{
g.drawString(ip1+"is a same string with different case"+ip2,20,95);
}
else if(ip1.compareTo(ip2)>0)
{
g.drawString(ip1+"is alphabetically greater than"+ip2,25,115);
}
else
{
g.drawString(ip1+"is alphabetically less than"+ip2);
}
g.drawString(Differece is: "+ip1.compareTo(ip2));
showStatus("Comparison of the two Strings.....");
}
public boolean action(Event e, Object o)
{
repaint();
return true;
}
}
Please rate the answer if it helped......Thnakyou
Hope it helps....
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.