Documentos de Académico
Documentos de Profesional
Documentos de Cultura
import javax.swing.JOptionPane;
// Calcular el promedio
double promedio = (numero1 + numero2 + numero3) / 3.0;
package segundavueta;
import javax.swing.JOptionPane;
public class Multiplicacion extends javax.swing.JFrame {
public Multiplicacion() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setText("Resultados:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(46, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
299, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(55, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
37, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55))
);
pack();
}// </editor-fold>
java.util.logging.Logger.getLogger(Multiplicacion.class.getName()).log(java.util.logging.Lev
el.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Multiplicacion.class.getName()).log(java.util.logging.Lev
el.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Multiplicacion.class.getName()).log(java.util.logging.Lev
el.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Multiplicacion.class.getName()).log(java.util.logging.Lev
el.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Multiplicacion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
3-. Que obtenga el perímetro y el área de un cuadrilátero (cuadrado o rectángulo) dada su
base y su altura y escribir los resultados.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public CalculadoraCuadrilatero() {
// Configuración de la ventana
setTitle("Calculadora de Cuadrilátero");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
add(new JLabel("Altura:"));
alturaField = new JTextField();
add(alturaField);
// Resultados
add(new JLabel("Área:"));
resultadoArea = new JTextField();
resultadoArea.setEditable(false);
add(resultadoArea);
add(new JLabel("Perímetro:"));
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Calcular")) {
// Obtener los valores de base y altura
double base = Double.parseDouble(baseField.getText());
double altura = Double.parseDouble(alturaField.getText());
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
btnCalcular.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double radio = Double.parseDouble(txtRadio.getText());
double altura = Double.parseDouble(txtAltura.getText());
frame.add(lblRadio);
frame.add(txtRadio);
frame.add(lblAltura);
frame.add(txtAltura);
frame.add(btnCalcular);
frame.add(resultado);
frame.pack();
frame.setVisible(true);
}
}
5-. Que dado un valor en metros, imprima su equivalente en yardas, pies, pulgadas,
centímetros.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public ConversorMetros() {
// Configurar la ventana
setTitle("Conversor de Metros");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// Crear componentes
metrosLabel = new JLabel("Metros:");
metrosLabel.setBounds(10, 10, 80, 20);
add(metrosLabel);
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Crear paneles
JPanel panel = new JPanel();
frame.add(panel);
// Crear etiquetas y campos de texto para ingresar los lados del triángulo
JLabel labelA = new JLabel("Lado A:");
JTextField textFieldA = new JTextField(10);
// Calcular el perímetro
double perimetro = ladoA + ladoB + ladoC;
public CalculadoraHipotenusa() {
setTitle("Calculadora de Hipotenusa");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calcularHipotenusa();
cateto1Field.setText("");
cateto2Field.setText("");
}
});
add(cateto1Label);
add(cateto1Field);
add(cateto2Label);
add(cateto2Field);
add(resultadoLabel);
add(resultadoField);
add(calcularButton);
setVisible(true);
}
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double velocidadKmH = Double.parseDouble(textField.getText());
double velocidadMS = velocidadKmH * 1000 / 3600; // Conversión de km/h a
m/s
resultLabel.setText("Velocidad en m/s: " + velocidadMS + " m/s");
} catch (NumberFormatException ex) {
resultLabel.setText("Por favor, ingrese una velocidad válida.");
}
}
});
frame.setVisible(true);
}
}
Funcionamiento:
9-. Desarrolle un programa que lea la velocidad en metros por segundo y la convierta a
kilómetros por hora.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double mps = Double.parseDouble(inputField.getText());
double kph = mps * 3.6; // Conversión de m/s a km/h
resultLabel.setText("Velocidad (km/h): " + kph);
} catch (NumberFormatException ex) {
resultLabel.setText("Ingrese una velocidad válida en m/s");
}
}
});
panel.add(label1);
panel.add(inputField);
panel.add(convertButton);
panel.add(resultLabel);
frame.add(panel);
frame.setVisible(true);
}
}
Funcionamiento
Programas con condicional
frame.add(boton);
boton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String numero1Str = JOptionPane.showInputDialog("Introduce el primer número
entero:");
String numero2Str = JOptionPane.showInputDialog("Introduce el segundo
número entero:");
try {
int numero1 = Integer.parseInt(numero1Str);
int numero2 = Integer.parseInt(numero2Str);
if (numero1 == numero2) {
JOptionPane.showMessageDialog(null, "Los números son iguales.");
} else {
JOptionPane.showMessageDialog(null, "Los números no son iguales.");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Ingresa números enteros válidos.");
}
}
});
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
Funcionamiento:
11-. Que permita leer un valor cualquiera N y escriba si dicho número es par o impar
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public ParImparChecker() {
// Configura la ventana
setTitle("Par o Impar Checker");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Crea componentes
inputField = new JTextField(10);
checkButton = new JButton("Verificar");
// Crea el panel
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Ingrese un número:"));
panel.add(inputField);
panel.add(checkButton);
import javax.swing.JOptionPane;
String mensaje;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
frame.add(label);
frame.add(textField);
frame.add(checkButton);
frame.add(resultLabel);
checkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int number = Integer.parseInt(textField.getText());
if (number % 2 == 0) {
resultLabel.setText(number + " es un número par.");
} else {
resultLabel.setText(number + " es un número impar.");
}
} catch (NumberFormatException ex) {
frame.setVisible(true);
}
}
14-. Que lea un número y determine si está entre 50 y 70.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
frame.add(label);
frame.add(textField);
frame.add(verificarButton);
verificarButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
try {
int numero = Integer.parseInt(input);
if (numero >= 50 && numero <= 70) {
JOptionPane.showMessageDialog(frame, "El número está entre 50 y 70.");
} else {
JOptionPane.showMessageDialog(frame, "El número no está en el rango
entre 50 y 70.");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Entrada no válida. Por favor, ingresa
un número válido.");
}
}
});
frame.pack();
frame.setVisible(true);
}
}
15- .Que permita leer tres valores: A, B y C respectivamente. Que muestre cuál es el
mayor y cuál es el menor. Como restricción considerar que los tres valores son distintos.
import javax.swing.JOptionPane;
// Leer el valor de A
inputA = JOptionPane.showInputDialog("Ingrese el valor de A:");
A = Double.parseDouble(inputA);
// Leer el valor de B
inputB = JOptionPane.showInputDialog("Ingrese el valor de B:");
B = Double.parseDouble(inputB);
// Leer el valor de C
inputC = JOptionPane.showInputDialog("Ingrese el valor de C:");
C = Double.parseDouble(inputC);
}
}
}
16-. Que permita convertir calificaciones numéricas, según la siguiente tabla:
a. A = 19 y 20,
b. B =16, 17 y 18,
c. C = 13, 14 y 15,
d. D = 10, 11 y 12,
e. E = 1 hasta el 9.
Se asume que la nota está comprendida entre 1 y 20.
import javax.swing.JOptionPane;
try {
int calificacion = Integer.parseInt(input);
if (esPrimo(n)) {
JOptionPane.showMessageDialog(null, n + " es un número primo.");
} else {
JOptionPane.showMessageDialog(null, n + " no es un número primo.");
}
}
frame.add(inputLabel);
frame.add(inputField);
frame.add(calculateButton);
frame.add(resultLabel);
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double horas = Double.parseDouble(inputField.getText());
int minutos = (int) (horas * 60);
int segundos = minutos * 60;
resultLabel.setText("En " + horas + " horas hay " + minutos + " minutos y " +
segundos + " segundos.");
} catch (NumberFormatException ex) {
resultLabel.setText("Por favor, ingrese un número válido.");
}
}
});
frame.setVisible(true);
}
}
19-. Que ingrese el sueldo del trabajador y aplicar un aumento del 10% si su sueldo es
menor a 1000
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
panel.add(label);
panel.add(sueldoTextField);
panel.add(calcularButton);
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double sueldo = Double.parseDouble(sueldoTextField.getText());
if (sueldo < 1000) {
sueldo += sueldo * 0.10; // Aplicar un aumento del 10%
JOptionPane.showMessageDialog(frame, "El nuevo sueldo con aumento es:
$" + sueldo);
} else {
JOptionPane.showMessageDialog(frame, "El sueldo no es elegible para un
aumento.");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Ingrese un valor numérico válido.");
}
}
});
frame.add(panel);
frame.setVisible(true);
}
}
20-. Que determine el pago a realizar por la entrada a un espectáculo donde se pueden
comprar solo hasta cuatro entradas, donde al costo de dos entradas se les descuenta el
10%, al de tres entrada el 15% y a la compra de cuatro tickets se le descuenta el 20 %.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public CalculadoraEntradas() {
setTitle("Calculadora de Entradas");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calcularPrecioEntradas();
}
});
add(panel);
setVisible(true);
}
verificarButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double calificacion = Double.parseDouble(calificacionField.getText());
int asistencia = Integer.parseInt(asistenciaField.getText());
frame.add(calificacionLabel);
frame.add(calificacionField);
frame.add(asistenciaLabel);
frame.add(asistenciaField);
frame.add(verificarButton);
frame.setVisible(true);
}
}
23-. Que capture un numero del 1 al 10 y mostrar en pantalla su equivalente en numero
romano
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public ConvertidorNumerosRomanos() {
setTitle("Convertidor de Números Romanos");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
convertirButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String numeroTexto = numeroTextField.getText();
try {
int numero = Integer.parseInt(numeroTexto);
if (numero >= 1 && numero <= 10) {
String numeroRomano = convertirANumeroRomano(numero);
resultadoLabel.setText("Resultado: " + numeroRomano);
} else {
resultadoLabel.setText("Número fuera de rango (1-10)");
}
} catch (NumberFormatException ex) {
resultadoLabel.setText("Entrada inválida. Ingrese un número del 1 al 10.");
}
}
});
add(panel);
}
panel.add(label);
panel.add(textField);
panel.add(calcularButton);
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double totalCompra = Double.parseDouble(textField.getText());
double descuento = 0.15; // 15%
if (totalCompra > 1000) {
double descuentoAplicado = totalCompra * descuento;
double totalConDescuento = totalCompra - descuentoAplicado;
JOptionPane.showMessageDialog(null, "El descuento aplicado es: $" +
descuentoAplicado + "\nTotal a pagar: $" + totalConDescuento);
} else {
JOptionPane.showMessageDialog(null, "No se aplica descuento. Total a
pagar: $" + totalCompra);
}
frame.setVisible(true);
}
}
25-. Que permita convertir una calificación en letra de acuerdo a la siguiente tabla:
10-A
9-B
8-C
7-D
6-E
5 o menos-F
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int calificacionNumerica = Integer.parseInt(inputField.getText());
frame.add(label);
frame.add(inputField);
frame.add(convertButton);
frame.add(resultLabel);
frame.pack();
frame.setVisible(true);
}
try {
// Convierte las entradas del usuario a números
double horasTrabajadas = Double.parseDouble(horasTrabajadasStr);
double sueldoPorHora = Double.parseDouble(sueldoPorHoraStr);
double horasExtras = Double.parseDouble(horasExtrasStr);
double bonoEstimulo = Double.parseDouble(bonoEstimuloStr);
frame.add(label);
frame.add(textField);
frame.add(calcularButton);
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String input = textField.getText();
int calificacion = Integer.parseInt(input);
if (calificacion == 100) {
resultado = "Excelente";
} else if (calificacion >= 90 && calificacion <= 99) {
resultado = "Muy bien";
} else if (calificacion >= 71 && calificacion <= 89) {
resultado = "Bien";
} else if (calificacion >= 70) {
resultado = "Suficiente";
} else {
resultado = "Insuficiente";
}
frame.pack();
frame.setVisible(true);
}
}
28-. Para calcular e imprimir el precio de un terreno del cual se tienen los siguientes
datos: largo, ancho y precio por metro cuadrado. Si el terreno tiene mas de 400 metros
cuadrados se hace un descuento del 10% .
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Este programa crea una ventana con campos de entrada para el largo, el ancho y el precio
por metro cuadrado del terreno, junto con un botón "Calcular Precio" que realiza los
cálculos y muestra el resultado en un cuadro de diálogo de JOptionPane. Si el área del
terreno es mayor a 400 metros cuadrados, se aplica un descuento del 10% en el precio
total.
2. Que determine cuantos segundos y minutos hay en N horas
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double horas = Double.parseDouble(horasTextField.getText());
int minutos = (int) (horas * 60);
int segundos = minutos * 60;
frame.add(horasLabel);
frame.add(horasTextField);
frame.add(calcularButton);
frame.add(resultadoLabel);
frame.setVisible(true);
}
}
3. Dado un tiempo en minutos, convertirlo a horas y minutos
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int minutos = Integer.parseInt(inputField.getText());
int horas = minutos / 60;
int minutosRestantes = minutos % 60;
frame.setVisible(true);
}
}
4. Calcule exactamente el número de días vividos por una persona hasta la fecha.
Contemplar los años bisiestos.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
public CalcularDiasVividos() {
super("Calculadora de Días Vividos");
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calcularDiasVividos();
}
});
int añosBisiestos = 0;
GregorianCalendar calendar = new GregorianCalendar();
for (int i = fechaNacimiento.getYear() + 1900; i <= fechaActual.getYear() + 1900; i++)
{
if (calendar.isLeapYear(i)) {
añosBisiestos++;
}
}