Slip4
Q1) Write a program to print an array after changing the rows and columns of a given two-dimensional array. [10 marks]
import java.util.Scanner;
public class Slip4_1{
public static void main(String[] args)
{
int[][] twodm = {
{10, 20, 30},
{40, 50, 60}
};
System.out.print("Original Array:\n");
print_array(twodm);
int[][] newtwodm = new int[twodm[0].length][twodm.length];
for (int i = 0; i < twodm.length; i++)
for (int j = 0; j < twodm[0].length; j++)
newtwodm[j][i] = twodm[i][j];
System.out.println("After changing the rows and columns of the said array:");
print_array(newtwodm);
}
static void print_array(int[][] twodm)
{
for (int i = 0; i < twodm.length; i++)
{
for (int j = 0; j < twodm[0].length; j++)
{
System.out.print(twodm[i][j] + " ");
}
System.out.println();
}
}
}
Q2) Write a program to design a screen using Awt that will take a user name and password. If the user name and password are not same, raise an Exception with appropriate message. User can have 3 login chances only. Use clear button to clear the TextFields.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class InvalidPasswordException extends Exception
{}
class A5SetB2 extends JFrame implements ActionListener
{
JLabel name, pass;
JTextField nameText;
JPasswordField passText;
JButton login, end;
static int cnt=0;
A5SetB2()
{
name = new JLabel("Name : ");
pass = new JLabel("Password : ");
nameText = new JTextField(20);
passText = new JPasswordField(20);
login = new JButton("Login");
end = new JButton("End");
login.addActionListener(this);
end.addActionListener(this);
setLayout(new GridLayout(3,2));
add(name);
add(nameText);
add(pass);
add(passText);
add(login);
add(end);
setTitle("Login Check");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==end)
{
System.exit(0);
}
if(e.getSource()==login)
{
try
{
String user = nameText.getText();
String pass = new String(passText.getPassword());
if(user.compareTo(pass)==0)
{
JOptionPane.showMessageDialog(null,"Login Successful","Login",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e1)
{
cnt++;
JOptionPane.showMessageDialog(null,"Login Failed","Login",JOptionPane.ERROR_MESSAGE);
nameText.setText("");
passText.setText("");
nameText.requestFocus();
if(cnt == 3)
{
JOptionPane.showMessageDialog(null,"3 Attempts Over","Login",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
}
public static void main(String args[])
{
new A5SetB2();
}
}
Comments
Post a Comment