Slip23
Q1) Define a class MyNumber having one private int data member. Write a default constructor to initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in main.Use command line arguments to pass a value to the Object. [10 marks]
class MyNumber
{
private int no;
MyNumber()
{
no=5;
}
MyNumber(int no)
{
this.no=no;
}
public void isNegative()
{
if(no<0)
System.out.println("Given number is negative");
}
public void isPositive()
{
if(no>0)
System.out.println("Given number is Positive");
}
public void isZero()
{
if(no==0)
System.out.println("Given number is Zero");
}
public void isOdd()
{
if(no%2!=0)
System.out.println("Given number is Odd");
}
public void isEven()
{
if(no%2==0)
System.out.println("Given is Even");
}
public static void main(String args[])
{
MyNumber n1=new MyNumber();
System.out.println(n1.no+" Details");
n1.isNegative();
n1.isPositive();
n1.isZero();
n1.isOdd();
n1.isEven();
int n=Integer.parseInt(args[0]);
MyNumber n2=new MyNumber(n);
System.out.println(n2.no+" Details");
n2.isNegative();
n2.isPositive();
n2.isZero();
n2.isOdd();
n2.isEven();
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class Slip23_2 extends JFrame{
// Conversion rates
double USD_TO_SGD = 1.41;
double USD_TO_EUR = 0.92;
double SGD_TO_EUR = 0.65;
JLabel sgdLabel,usdLabel,eurLabel;
JTextField usdField,sgdField,eurField ;
public static void main(String[] args)
{
new Slip23_2();
}
// Create a new frame (window)
Slip23_2()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
sgdLabel = new JLabel("Singapore Dollars");
sgdField = new JTextField();
usdLabel = new JLabel("US Dollars");
usdField = new JTextField();
usdField.setEditable(false);
eurLabel = new JLabel("Euros");
eurField = new JTextField();
eurField.setEditable(false);
setLayout(new GridLayout(3,2,5,5));
sgdField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double sgdAmount = Double.parseDouble(sgdField.getText());
// Perform conversions
double usdAmount = sgdAmount / USD_TO_SGD;
double eurAmount = sgdAmount * SGD_TO_EUR;
// Format the output to two decimal places
DecimalFormat df = new DecimalFormat("#.00");
usdField.setText(df.format(usdAmount));
eurField.setText(df.format(eurAmount));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
}
}
});
add(sgdLabel);
add(sgdField);
add(usdLabel);
add(usdField);
add(eurLabel);
add(eurField);
setVisible(true);
}
}
Comments
Post a Comment