Programs 042734

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Programs

Write a java program to implement a Frame


application to compute the sum of two
numbers using AWT controls.
import java.awt.*;
// Button
import java.awt.event.*;
addButton = new Button("Add");
public class SumFrameApp extends Frame implements ActionListener {
addButton.addActionListener(this);
Label label1, label2, label3;
TextField text1, text2, result;
Button addButton; // Adding components to Frame
public SumFrameApp() { add(label1);
// Frame setup add(text1);
setLayout(new FlowLayout());
setSize(300, 200); add(label2);
setTitle("Sum Calculator"); add(text2);
// Labels
add(addButton);
label1 = new Label("Enter first number:"); add(label3);
label2 = new Label("Enter second number:");
label3 = new Label("Result:");
add(result);

// Text Fields
text1 = new TextField(10);
// Frame visibility
text2 = new TextField(10); setVisible(true);
result = new TextField(10);
result.setEditable(false);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
// Parsing numbers from text fields
int num1 = Integer.parseInt(text1.getText());
int num2 = Integer.parseInt(text2.getText());

// Computing sum
int sum = num1 + num2;

// Displaying result
result.setText(String.valueOf(sum));
} catch (NumberFormatException ex) {
result.setText("Invalid input");
}
}

public static void main(String[] args) {


new SumFrameApp();
}
}
Write a java program to implement string
methods for the following task:

i) To check two strings are equal


ii) To convert to a character array
iii) To remove leading and trailing spaces.
public class StringMethods {

// Method to check if two strings are equal


public static boolean areStringsEqual(String str1, String str2) {
return str1.equals(str2);
}

// Method to convert a string to a character array


public static char[] convertToCharArray(String str) {
return str.toCharArray();
}

// Method to remove leading and trailing spaces from a string


public static String trimSpaces(String str) {
return str.trim();
}
public static void main(String[] args) {
// Example strings
String string1 = " Hello World ";
String string2 = "Hello World";
String string3 = " Hello World ";

// i) Check if two strings are equal


System.out.println("Are string1 and string2 equal? " + areStringsEqual(string1, string2));
System.out.println("Are string1 and string3 equal? " + areStringsEqual(string1, string3));

// ii) Convert string to a character array


char[] charArray = convertToCharArray(string1);
System.out.print("Character array of string1: ");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println();

// iii) Remove leading and trailing spaces


System.out.println("String1 with trimmed spaces: '" + trimSpaces(string1) + "'");
}
}

You might also like