Programa para sumar
Script
const sumar = (a, b) => {
return a + b;
}
sumar(1, 2);
All generations.
Script
const sumar = (a, b) => {
return a + b;
}
sumar(1, 2);
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number1;
int number2;
int result;
int option;
System.out.println("Please select an option (1-5):");
System.out.println("1. Add numbers");
System.out.println("2. Substract numbers");
System.out.println("3. Multiply numbers");
System.out.println("4. Divide numbers");
System.out.println("5. Exit\n");
System.out.println("Option: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("Addition");
System.out.println("Enter first integer: ");
number1 = sc.nextInt();
System.out.println("Enter second integer: ");
number2 = sc.nextInt();
result =
## 1. Sumar
void accionBoton(ActionEvent evt) {
String nombre = evt.getActionCommand();
if(nombre.equals("eliminar")) {
int fila = t.getSelectedRow();
int id = (int) t.getValueAt(fila, 0);
if(fila > -1) {
try {
String sSQL = "DELETE FROM `producto` WHERE `producto`.`id` = ?";
PreparedStatement pst = cn.prepareStatement(sSQL);
pst.setInt(1, id);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Eliminado");
limpiarCampos();
setFilas();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al Eliminar" + e);
}
} else {
JOptionPane.showMessageDialog(null, "No selecciono ninguna fil
Script
function defaultSwitch(e) {
switch (e) {
case "a":
console.log("a");
break;
case "b":
console.log("b");
break;
default:
return defaultSwitch(prompt("pick a or b"));
}
}
Script
function menu(){
const $btn_cita = document.querySelector("#btn_cita");
$btn_cita.addEventListener("click", () =>{
console.log("cita creada");
})
}
menu()
public String getNombre() {
return Nombre;
}
public String getApellido() {
return Apellido;
}
delete(int id)
def suma(a,b):
return a+b
Script
function eliminar(id){
$.ajax({
url: 'eliminar.php',
type: 'post',
data: 'id=' + id,
success: function(respuesta) {
$('#'+id).remove();
alert(respuesta);
}
});
}
public void delete(int n) {
String sql = "DELETE FROM product WHERE id =?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, n);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
String codigo = txtCedula.getText();
int codigo2 = Integer.parseInt(codigo);
String sql = "DELETE FROM clientes WHERE codigo=codigo2";
try {
PreparedStatement pst = cn.prepareStatement(sql);
int n = pst.executeUpdate();
if (n > 0) {
JOptionPane.showMessageDialog(null, "Dato eliminado");
limpiar();
}
} catch (SQLException ex) {
Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
}
}
Script
function menu(){
//imprime todas las opciones
console.log(''+
'1. Sumar \n'+
'2. Restar \n'+
'3. Multiplicar \n'+
'4. Dividir \n'+
'5. Salir \n');
}
menu();
Script
console.log(add(1, 2))
Script
function supportMenu(name) {
// this is where we will build the support menu
let menu = "";
// this is where we will create the contact info
let contactInfo = "";
// Create the header of the menu
menu = "Hello " + name + ", what can we do for you? \n";
menu += "1. Can you make the text bigger?\n";
menu += "2. I can't save my file.\n";
menu += "3. Nothing, I'm just bored\n";
// Create the contact info
contactInfo = "\n\nPlease contact us at support@greenfoxacademy.com for further assistance.";
// Add the contact info to the menu
menu += contactInfo;
return menu;
}
Script
function getResults(keyword, page) {
var url = 'https://www.googleapis.com/books/v1/volumes?q=' + keyword + '&page=' + page;
return fetch(url) // get data and parse as JSON
.then(function(response) {
return response.json();
})
}
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
def modulus(a, b):
return a % b
def power(a, b):
return a ** b
def main():
while True:
option = str(input('\n\nSelect an option:\n1) Add\n2) Subtract\n3) Multiply\n4) Divide\n5) Modulus\n6) Power\n7) Exit\n\n'))
if option == '1':
a = int(input('\nPlease enter first number: '))
b = int(input('\nPlease enter second number: '))
print('\nThe result is:', add(a, b))
elif option == '2':
a = int(input('\nPlease enter first number: '))
b =
Script
const createSupportTicket = () => {
// 1. create the div element
const supportTicketDiv = document.createElement('div');
supportTicketDiv.setAttribute('class', 'support-ticket');
// 2. Create the elements inside the div element
const title = document.createElement('h3');
title.appendChild(document.createTextNode('Soporte de Tecnico'));
const description = document.createElement('p');
description.appendChild(document.createTextNode('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla auctor tellus at dui porttitor porta'));
const delBtn = document.createElement('button');
delBtn.appendChild(document.createTextNode('Eliminar'));
delBtn.setAttribute('class', 'btn btn-del-ticket');
const closeBtn = document.createElement('button');
closeBtn.appendChild(document.create
Script
function createApoyo(){
console.log("Crear cita de soporte tecnico");
}
public void consultar(String nombre) {
try {
//create connection
Class.forName(driver);
Connection conexion = DriverManager.getConnection(url, sqlUser, sqlPassword);
Statement st = conexion.createStatement();
//create query
String sql = "SELECT * FROM usuario WHERE nombre = '" + nombre + "'";
ResultSet rs = st.executeQuery(sql);
//print result
while (rs.next()) {
System.out.println(rs.getString("nombre"));
}
//close connection
st.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
package com.cheatsheet;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
public void Sumar(int num1, int num2)
{
int suma = num1 + num2;
System.out.println("La suma es: " + suma);
}
public void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
PreparedStatement pst = null;
String codigo = txtEliminar.getText();
String sql = "DELETE FROM CLIENTE WHERE CODIGO =" + codigo;
try {
con = getConnection();
pst = con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Cliente Eliminado con Exito");
} catch (SQLException ex) {
Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
Script
function pow(a, b) {
if(typeof b !== "number") {
b = 2;
}
return a ** b;
}
pow(9, 2);
Script
function createSupportTicket(){
console.log("Creating a support ticket.");
}
switch (opt) {
case 1:
dosTres();
break;
case 2:
tresCuatro();
break;
case 3:
tresCuatro();
break;
case 4:
break;
default:
System.out.println("Opcion no valida");
dosTres();
break;
}
def eliminar(nombre, codigo):
try:
cursor.execute("DELETE FROM PRODUCTOS WHERE nombre = '" + nombre + "' AND codigoproducto = '" + codigo + "';")
conexion.commit()
print("Dato eliminado")
except:
print("Error")
nombre = "Laptop"
codigo = "222222"
eliminar(nombre, codigo)
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = tableEstudiantes.getSelectedRow();
if(row>=0){
int opt=JOptionPane.showConfirmDialog(null, "Eliminar?","Eliminar",JOptionPane.YES_NO_OPTION);
if (opt==JOptionPane.YES_OPTION){
String codigo=(tableEstudiantes.getValueAt(row, 0).toString());
try {
PreparedStatement pst=cn.prepareStatement("DELETE FROM estudiantes WHERE codigo='"+codigo+"'");
pst.executeUpdate();
mostrarDatos("");
JOptionPane.showMessageDialog(null, "Eliminado");
} catch (SQLException ex) {
Logger.getLogger(Ventana.class.getName()).log
public void llenarTabla() {
try {
DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
modelo.setRowCount(0);
st = con.conexion();
st = con.conexion().createStatement();
rs = st.executeQuery("SELECT * FROM productos");
while (rs.next()) {
modelo.addRow(new Object[]{rs.getString("id"), rs.getString("nombre"), rs.getString("descripcion"), rs.getString("precio")});
}
jTable1.setModel(modelo);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error al llenar la tabla");
}
}
// Para objetos
function foo(input) {
// do something with the input
return input
}
var result = foo(123) // result is 123
var result2 = foo() // result is undefined
// Para strings
function bar(input) {
return input || 'default value'
}
var result3 = bar(123) // result is 123
var result4 = bar() // result is 'default value'
// Para numbers
function baz(input) {
return input !== undefined ? input : 0
}
var result5 = baz(123) // result is 123
var result6 = baz() // result is 0
Script
function addAppointment(name) {
return `
<div class="row">
<div class="col-md-12">
<div class="card card-body">
<h2>${name}</h2>
</div>
</div>
</div>
`
}
public class delete extends ActionPerformed{
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String sql = "DELETE FROM tbl_producto WHERE codigo = ?";
PreparedStatement ps = conn.prepareStatement(sql);
String producto.text = codigo;
ps.setString(1, producto.text);
ps.execute();
}
}
}
private void btnCrearCitaActionPerformed(java.awt.event.ActionEvent evt) {
String c = "", h = "";
try {
c = fechaCita.getCalendar().getTime().toString();
h = txtHora.getText().toString();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Seleccione la fecha");
return;
}
c = c.substring(0, c.length() - 6);
h = h.substring(0, h.length() - 3);
String date = c + " " + h;
int id_usuario = listaUsuarios.get(cmbUsuario.getSelectedIndex()).getId_usuario();
int id_soporte = listaSoportes.get(cmbSoporte.getSelectedIndex()).getId_soporte();
cita = new Cita
Script
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('tableId').deleteRow(i);
}
Script
function add(a, b) {
if (a && b) {
return a + b
}
return 0
}
add(1)
Script
function menu() {
var option = prompt("Que operacion desea hacer? \n 1.- Sumar \n 2.- Restar \n 3.- Multiplicar \n 4.- Dividir");
var num1 = prompt("Escribe el primer numero");
var num2 = prompt("Escribe el segundo numero");
if (option === "1") {
alert(Number(num1) + Number(num2));
}
}
private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {
String modelo=cbxModelo.getSelectedItem().toString();
switch(modelo){
case "Clasico":
new VentanaRegistroClasico().setVisible(true);
break;
case "Deportivo":
new VentanaRegistroDeportivo().setVisible(true);
break;
case "Automatico":
new VentanaRegistroAutomatico().setVisible(true);
break;
case "Familiar":
new VentanaRegistroFamiliar().setVisible(true);
break;
case "Personalizado":
new VentanaRegistroPersonalizado().setVisible(true);
break;
}
}
//Algoritmo
function btnEliminarActionPerformed(ActionEvent evt){
eliminarEstudiante(codigo)
}
function eliminarEstudiante(String codigo){
records = getEstudiante(codigo)
if(records.length > 0){
//Elimina la primer fila que encuentre
delete(records[0])
}
}
function getEstudiante(String codigo){
//busca en la tabla estudiante y retorna un array de records
//select * from estudiante where codigo = codigo
return estudianteTable;
}
Script
function createItem(description, price) {
return {
description,
price
}
}
const item = createItem('Tablet', 300)
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnEliminar) {
try {
String sql = "DELETE FROM registro WHERE id = ?";
PreparedStatement st = conexion.prepareStatement(sql);
st.setInt(1, Integer.parseInt(this.txtID.getText()));
st.executeUpdate();
updateTable();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
PreparedStatement pps = cn.prepareStatement("DELETE FROM registro WHERE codigo="+jTextField_codigo.getText());
pps.executeUpdate();
JOptionPane.showMessageDialog(null,"Dato eliminado");
} catch (SQLException ex) {
Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
}
}
public User getUserByEmail(String email) {
Query query = getSession().createQuery("from User where email = :email");
query.setParameter("email", email);
return (User) query.uniqueResult();
}
Script
function sumar(a,b){
return a + b
}
function restar(a,b){
return a - b
}
function multiplicar(a,b){
return a * b
}
function dividir(a,b){
return a / b
}
operacion = "";
while(operacion != "salir"){
console.log("Menu")
console.log("1.- Sumar")
console.log("2.- Restar")
console.log("3.- Multiplicar")
console.log("4.- Dividir")
console.log("5.- Salir")
operacion = prompt("Ingresa el numero de la opción")
if(operacion == "sumar"){
num1 = Number(prompt("Ingresa el primer número"))
num2 = Number(prompt("Ingresa el segundo número"))
console.log(sumar(num1,num2))
}
else if(operacion == "
private void itemCreateAppointmentActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
new CreateAppointment().setVisible(true);
this.dispose();
}
Script
var readlineSync = require('readline-sync');
var options = ['Sumar', 'Restar', 'Multiplicar', 'Dividir', 'Salir'];
while (true) {
var index = readlineSync.keyInSelect(options, 'Que desea hacer?');
if (options[index] === 'Sumar') {
var a = readlineSync.questionInt('Numero 1: ');
var b = readlineSync.questionInt('Numero 2: ');
console.log('Resultado: ' + (a + b));
}
if (options[index] === 'Restar') {
var a = readlineSync.questionInt('Numero 1: ');
var b = readlineSync.questionInt('Numero 2: ');
console.log('Resultado: ' + (a - b));
}
if (options[index] === 'Multiplicar') {
var a = readlineSync.questionInt('Numero 1: ');
var b = read
try {
String sql = "DELETE FROM tabla1 WHERE id = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Persona eliminada!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
void actionPerformed(ActionEvent e) {
try {
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
String query = "delete from empleado where id = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, id);
preparedStmt.execute();
conn.close();
} catch (Exception e1) {
System.err.println("Got an exception!");
System.err.println(e1.getMessage());
}
}
def nombre():
nombre = input("Dame tu nombre")
return nombre
nombre()
Script
function hola(nombre) {
return `hola ${nombre}`
}
@Override
public void actionPerformed(ActionEvent a){
if (a.getSource() == btnRegistrar) {
String nombre = txtNombre.getText();
String apellido = txtApellido.getText();
String contraseña = txtContraseña.getText();
String correo = txtCorreo.getText();
String tipo = (String) cmbTipo.getSelectedItem();
if (tipo.equals("Seleccionar Tipo")) {
JOptionPane.showMessageDialog(null, "Por favor seleccione un tipo");
} else {
Usuario usu = new Usuario();
usu.setNombre(nombre);
usu.setApellido(apellido);
usu.setContraseña(contraseña);
usu.setCorreo(correo);
usu.setTipo(tipo);
usuarios.
import java.util.Scanner;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
int a, b;
Scanner in = new Scanner(System.in);
try {
System.out.println("Enter a number: ");
a = in.nextInt();
System.out.println("Enter another number: ");
b = in.nextInt();
System.out.println("Result: " + (a + b));
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
System.out.println("Sum not calculated!");
}
}
}
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int option = 0;
int x = 0;
int y = 0;
int result = 0;
boolean exit = false;
while (!exit) {
System.out.println("1. Sumar");
System.out.println("2. Restar");
System.out.println("3. Multiplicar");
System.out.println("4. Dividir");
System.out.println("5. Salir");
option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("Ingrese el primer número");
x = scanner.nextInt();
System.out.println("Ingrese el segundo número");
y = scanner.nextInt();
result = x+y;
break;
case 2:
System.out
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String valor = (String) jComboBox1.getSelectedItem();
String valor2 = (String) jComboBox2.getSelectedItem();
String valor3 = (String) jComboBox3.getSelectedItem();
String valor4 = (String) jComboBox4.getSelectedItem();
String valor5 = (String) jComboBox5.getSelectedItem();
JOptionPane.showMessageDialog(null,"Usted ha seleccionado lo siguiente: \n" + "1: " + valor + "\n2: " + valor2 + "\n3: " + valor3 + "\n4: " + valor4 + "\n5: " + valor5);
}
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String codigo = txtCodigo.getText();
int pos = 0;
for (int i = 0; i < listaEstudiantes.size(); i++) {
if(listaEstudiantes.get(i).getCodigo().equalsIgnoreCase(codigo)){
pos = i;
}
}
listaEstudiantes.remove(pos);
JOptionPane.showMessageDialog(this, "Estudiante Eliminado", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
mostrarListaElementos();
}
// el jComboBox
String[] lista = {"Uno", "Dos", "Tres", "Cuatro", "Cinco"};
JComboBox combo = new JComboBox(lista);
JButton button = new JButton("registrar");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String selected = (String)combo.getSelectedItem();
System.out.println(selected);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String valor = jComboBox1.getSelectedItem().toString();
Script
function add(a, b) {
return a + b;
}
// Java
public void crearCitaSoporteTecnico(View view){
// code here
}
private void jButtonRegistrarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int dni = Integer.parseInt(this.jTextFieldDni.getText());
String nombre=this.jTextFieldNombre.getText();
String apellido = this.jTextFieldApellido.getText();
String fechadenacimiento = this.jTextFieldFechaDeNacimiento.getText();
String domicilio = this.jTextFieldDomicilio.getText();
String telefono = this.jTextFieldTelefono.getText();
String email = this.jTextFieldEmail.getText();
String sexo = this.jComboBox1.getSelectedItem().toString();
String estadocivil = this.jComboBox2.getSelectedItem().toString();
String tipodecarga = this.jComboBox3.getSelectedItem
public List<Customer> getCustomer(){
List<Customer> customers = new ArrayList<>();
customers.add(new Customer(id, name, surname))
return customers
}
public Customer findById(id){
return customerRepository.findById(id);
}
Script
function create_menu(){
var body = document.getElementsByTagName('body')[0];
var menu = document.createElement('div');
menu.id = 'menu';
body.appendChild(menu);
menu.innerHTML = `
<div class="container">
<div class="row">
<div class="col-12">
<nav class="navbar navbar-expand-lg navbar-light">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Inicio <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Citas</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reportes</a>
</li>
<li class="nav-item
public void Eliminar(int codigo) {
try {
con = new Conexion();
String sql = "DELETE FROM productos WHERE codigo = ?";
ps = con.getConexion().prepareStatement(sql);
ps.setInt(1, codigo);
ps.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
public void onClick(View v) {
Toast.makeText(this, "Button is clicked", Toast.LENGTH_SHORT).show();
}
public void Registro() {
String producto = (String) boxProducto.getSelectedItem();
String marca = (String) boxMarca.getSelectedItem();
String categoria = (String) boxCategoria.getSelectedItem();
String unidad = (String) boxUnidad.getSelectedItem();
if (txtCodigo.getText().isEmpty()||txtDescripcion.getText().isEmpty()||txtCantidad.getText().isEmpty()||txtPrecio.getText().isEmpty()||txtPrecioCompra.getText().isEmpty()||txtPrecioVenta.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Campos Obligatorios Vacios");
} else {
sql = "INSERT INTO producto (CODIGO, PRODUCTO, MARCA, CATEGORIA, DESCRIPCION, EXISTENCIA, UNIDAD, PRECIO_COMPRA, PRECIO_VENTA, PRECIO_
Script
function(a, b){
return a + b
}
private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String nombre = txtNombre.getText();
String apellido = txtApellido.getText();
String direccion = txtDireccion.getText();
String telefono = txtTelefono.getText();
String email = txtEmail.getText();
String tipoSangre = cmbTipoSangre.getSelectedItem().toString();
String sexo = "";
if (rbtHombre.isSelected()) {
sexo = "Hombre";
} else if (rbtMujer.isSelected()) {
sexo = "Mujer";
}
String fechaNacimiento = txtFechaNacimiento.getText();
Persona p = new Persona(nombre, apellido, direccion, telef
switch(c) {
case 1:
break;
case 2:
break;
default:
continue;
}
Scanner sc = new Scanner(System.in);
String input = sc.next();
private void eliminarActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "DELETE FROM datos WHERE id=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1,Integer.parseInt(id.getText()));
pst.execute();
JOptionPane.showMessageDialog(null,"Eliminado exitosamente");
}catch(Exception e){
JOptionPane.showMessageDialog(null,"No se ha podido eliminar");
}
mostrarDatos();
}
try {
Connection cn = con.Conectar();
PreparedStatement pst = cn.prepareStatement("delete from Alumnos where codigo = ?");
pst.setString(1, txt_buscarCodigo.getText().trim());
pst.executeUpdate();
txt_buscarCodigo.setText("");
JOptionPane.showMessageDialog(null, "Eliminacion Completa");
} catch (Exception e) {
}
Script
function add(a, b = 1) {
return a + b;
}
add(1, 2);
Script
function sum(a, b=0) {
return a + b;
}
sum(1);
String numberToWords(int num) {
if (num == 0)
return "Zero";
int billion = num / 1000000000;
int million = (num - billion * 1000000000) / 1000000;
int thousand = (num - billion * 1000000000 - million * 1000000) / 1000;
int rest = num - billion * 1000000000 - million * 1000000 - thousand * 1000;
String result = "";
if (billion != 0)
result = threeDigit(billion) + " Billion";
if (million != 0) {
if (!result.isEmpty())
result += " ";
result += threeDigit(million) + " Million";
}
if (thousand != 0) {
if (!result.isEmpty())
result += " ";
result += threeDigit(thousand) + " Thousand";
}
if (rest != 0) {
if (!result.isEmpty())
result += " ";
result += threeDigit(rest);
}
return result
import java.util.Scanner;
public class misclase{
public static void main(String []args){}
}
Script
function showMenu() {
console.log("1. Sumar")
console.log("2. Restar")
console.log("3. Multiplicar")
console.log("4. Dividir")
console.log("5. Salir")
}
public String consultar(){
try {
String sql="select * from usuario where user='"+user+"'";
ResultSet rs;
rs = st.executeQuery(sql);
if(rs.next()){
return "usuario existente";
}else{
return "usuario inexistente";
}
} catch (Exception e) {
return "error";
}
}
Script
def add(a, b):
return a + b
add(1, 2)
def add(a, b):
try:
return a + b
except Exception as e:
print("Ocurrio un error", e)
add(1, "2")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int numero = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de registro"));
if (numero > 0 && numero <= reg) {
int posicion = numero - 1;
registros[posicion] = null;
JOptionPane.showMessageDialog(null, "Se elimino el registro numero: " + numero);
} else {
JOptionPane.showMessageDialog(null, "Numero de registro invalido");
}
} catch (java.lang.NumberFormatException e) {
JOptionPane.showMessageDialog(null, "El formato de entrada es incorrecto");
}
}
public void cargarComboBox(){
try {
String sentencia = "SELECT * FROM tabla";
ResultSet resutlado = conexion.createStatement().executeQuery(sentencia);
while(resutlado.next()){
jComboBox1.addItem(resutlado.getString("columna"));
}
} catch (Exception e) {
}
}
Script
function addNumbers(a, b) {
if (a && b) {
return a + b
}
return 'a or b is undefined'
}
import javax.swing.JComboBox;
String[] colores = { "Rojo", "Verde", "Azul" };
JComboBox<String> color = new JComboBox<String>(colores);
Script
function add(a, b) {
return a + b
}
add(1, 2)
public static int suma(int a, int b)
return a+b;
System.out.println(suma(2,3));
void solicitarNombre(){
System.out.print("Ingrese su nombre: ");
String nombre;
nombre = entrada.nextLine();
System.out.println("Su nombre es: " + nombre);
}
public void Registrar(ActionEvent e){
String tipo = jComboBox1.getSelectedItem().toString();
if (tipo.equalsIgnoreCase("tipo1")){
//...
}else if (tipo.equalsIgnoreCase("tipo2")){
//...
}else if (tipo.equalsIgnoreCase("tipo3")){
//...
}
}
String str = scanner.next();
private void btnregistrarActionPerformed(java.awt.event.ActionEvent evt) {
String categoria = cmbcat.getSelectedItem().toString();
String marca = cmbmarca.getSelectedItem().toString();
String modelo = cmbmodelo.getSelectedItem().toString();
String color = cmbcolor.getSelectedItem().toString();
String anio = cmbanio.getSelectedItem().toString();
String tipo = cmbtipo.getSelectedItem().toString();
String motor = cmbmotor.getSelectedItem().toString();
String cilindraje = cmbcilindraje.getSelectedItem().toString();
String transmision = cmbtrans.getSelectedItem().toString();
String placa = txtplaca.getText().toUpperCase();
String nombre = txtnombre.getText();
String direccion = txtdireccion.getText
private static void eliminarActionPerformed(java.awt.event.ActionEvent evt) {
String nombre = txtNombre.getText();
try {
PreparedStatement pst = cn.prepareStatement("DELETE FROM clientes WHERE nombre='"+nombre+"'");
pst.executeUpdate();
mostrardatos("");
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
Script
const getUser = (id) => {
return new Promise((resolve, reject) => {
connection.query(
'SELECT * FROM users WHERE id = ?',
[id],
(error, results, fields) => {
if (error) {
return reject(error);
}
return resolve(results[0]);
},
);
});
};
Scanner p = new Scanner(System.in);
int n1, n2, suma;
System.out.println("Ingrese numero 1: ");
n1 = p.nextInt();
System.out.println("Ingrese numero 2: ");
n2 = p.nextInt();
suma = n1 + n2;
System.out.println("La suma es: " + suma);
switch(foo) {
case 1:
doSomething();
case 2:
doSomethingElse();
break;
default:
console.log('blabla');
return;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost/bd_prestamo", "root", "");
PreparedStatement pst = cn.prepareStatement("delete from tipos_prestamos where codigo_tipo_prestamo = ?");
pst.setString(1, txt_codigo.getText().trim());
pst.executeUpdate();
txt_codigo.setText("");
txt_descripcion.setText("");
JOptionPane.showMessageDialog(this, "REGISTRO ELIMINADO.", "Eliminado", JOptionPane.INFORMATION_MESSAGE);
btnEliminar.setEnabled(false);
txt_codigo.setEnabled(true);
txt_descripc
class HolaMundo
{
public static void main(String args[])
{
Console.Write("Cual es tu nombre: ");
String nombre = Console.ReadLine();
Console.Write("Hola " + nombre);
}
}
Script
let option = prompt("1. crear cita
2. salir")
if (option == 1){
var cita = prompt("crear cita")
}
else {
return "Fin"
}
int row = tableEstudiante.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(this, "Debe seleccionar una fila de la tabla");
return;
}
int id = Integer.parseInt(tableEstudiante.getValueAt(row, 0).toString());
if (JOptionPane.showConfirmDialog(this, "Desea eliminar este registro?",
"Eliminar registro", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
EstudianteDAO.eliminar(id);
JOptionPane.showMessageDialog(this, "El registro ha sido eliminado");
estudianteTableController.updateTable();
}
def sum():
a = input("Ingrese numero 1: ")
b = input("Ingrese numero 2: ")
return a + b
def menu():
print("1. Sumar")
print("2. Restar")
print("3. Multiplicar")
print("4. Dividir")
print("5. Salir")
choice = int(input("Introduce una opción: "))
return choice
def suma(a,b):
return a + b
def resta(a,b):
return a - b
def multiplicacion(a,b):
return a*b
def division(a,b):
return a/b
while True:
choice = menu()
if choice == 1:
a = float(input("Introduce el primer numero: "))
b = float(input("Introduce el segundo numero: "))
print("El resultado es: ", suma(a,b))
continue
elif choice == 2:
a = float(input("Introduce el primer numero: "))
b = float(input("Introduce el seg
switch(opc) {
case 1:
/*
código para ingresar un nuevo producto
*/
break;
case 2:
/*
código para mostrar un listado de productos
*/
break;
default:
return catalogo_productos();
break;
}
public void actionPerformed(ActionEvent e) {
int index=cbx.getSelectedIndex();
System.out.println(index);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
try{
String n=t1.getText();
String q="delete from student where rollno="+n;
Statement stm=con.createStatement();
stm.executeUpdate(q);
JOptionPane.showMessageDialog(null,"Record Deleted");
}
catch(Exception ee){
JOptionPane.showMessageDialog(null,"Record Not Deleted");
}
}
String name = JOptionPane.showInputDialog("What is your name?");
public class MenuCalculadora {
public static void main(String[] args) {
int choice;
Scanner s = new Scanner(System.in);
do {
System.out.println("\nMENU: ");
System.out.println("1.Suma");
System.out.println("2.Resta");
System.out.println("3.Salir");
System.out.println("Ingrese su opción: ");
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println("Agregar función Suma");
break;
case 2:
System.out.println("Agregar función Resta");
break;
case 3:
System.out.println("Salir");
break;
default:
System.out.println("Opción incorrecta.");
}
} while (choice != 3);
}
}
public void getUser(String username, String password) {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT name, email FROM User WHERE username = '" + username + "' AND password = '" + password + "'");
if (resultSet.next()) {
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println(name);
System.out.println(email);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Script
function delete_()
{
document.getElementById("texto").value = "";
}
public String llamar(String nombre) {
if (nombre == null) {
return "Error";
}
return "Hola " + nombre;
}
public static void main(String[] args) {
String selection = JOptionPane.showInputDialog(null, "What is your favourite kind of cheese?",
"Cheese Selector", JOptionPane.QUESTION_MESSAGE, null, // Use
// default
// icon
new Object[] { "Brie", "Cheddar", "Gouda", "Roquefort", "Swiss" },
"Cheddar").toString();
switch (selection) {
case "Brie":
System.out.println("You chose Brie!");
break;
case "Cheddar":
System.out.println("You chose Cheddar!");
break;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1. Sumar");
System.out.println("2. Restar");
System.out.println("3. Multiplicar");
System.out.println("4. Dividir");
System.out.println("5. Salir");
System.out.println("Ingrese una opción: ");
int opcion = sc.nextInt();
int num1, num2;
switch (opcion) {
case 1:
System.out.println("Ingrese el primer numero:");
num1 = sc.nextInt();
System.out.println("Ingrese el segundo numero:");
num2 = sc.nextInt();
System.out.println("El resultado es: " + (num1 + num2));
break;
case 2:
System.out.println("Ingrese el primer numero:"
public static String capitalize(String s) {
if (s.length() == 0) {
return "";
} else if (s.length() == 1) {
return s.toUpperCase();
} else {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
capitalize("hey friends! practice practice practice!")
Script
function menu() {
return "1 => Sumar\n" +
"2 => Restar\n" +
"3 => Multiplicar\n" +
"4 => Dividir\n" +
"5 => Salir\n"
}
function opcion(value) {
switch(parseInt(value)) {
case 1:
return menu();
case 2:
return menu();
case 3:
return menu();
case 4:
return menu();
case 5:
return "Gracias por usar este programa";
}
}
opcion(prompt("Escoja una opcion del menu\n" + menu()))
function add(a, b):
return a + b
Script
function getAnimals(animal = 'panda') {
return animal
}
getAnimals('tiger')
public function create_cita():
return "Una cita fue creada"
create_cita()
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String codigo = txtCodigo.getText();
int cod = Integer.parseInt(codigo);
E.EliminarE(cod);
try {
String [] titulos = {"Codigo", "Nombre", "Apellido", "Telefono"};
String sql = "SELECT * FROM estudiante";
model = new DefaultTableModel(null, titulos);
Estudiante = E.consultaEstudiante(sql);
String [] fila = new String[4];
for(int i = 0; i < Estudiante.size(); i++)
{
fila[0] = Estudiante.get(i).getCodigo()+ "";
fila[1] = Estudiante.get(i).getNombre();
fila[2] =
Script
function comoAgregoQueUnIntSeaParaPalabras(num) {
var ordinal = ["th", "st", "nd", "rd"];
var a = num % 100;
return num + (ordinal[(a - 20) % 10] || ordinal[a] || ordinal[0]);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
frame = new JFrame();
JButton button = new JButton("Crear cita");
button.setBounds(100, 100, 140, 40);
frame.add(button);
frame.setSize(300, 400);
frame.setLayout(null);
frame.setVisible(true);
}
def main():
print("1) Sumar")
print("2) Restar")
print("3) Multiplicar")
print("4) Dividir")
print("5) Salir")
choice = int(input("Seleccione una opción: "))
if choice in ( 1, 2, 3, 4):
num1 = int(input("Ingrese el primer número: "))
num2 = int(input("Ingrese el segundo número: "))
if choice == 1:
print(num1, "+", num2, "=", add(num1, num2))
elif choice == 2:
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == 3:
print(num1, "*", num2, "=", multiply(num1, num2))
else:
print(num1, "/", num2, "=", divide(num1, num
Script
function solicitarNombre() {
console.log('hola')
}
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
def menu():
print("\nCalculator\n")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Quit")
print("Enter 'x' to exit.")
while True:
menu()
choice = input("Enter choice(1/2/3/4/5): ")
if choice == '5':
break
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if choice == '1':
print(a, "+", b, "=", add(a,b))
elif choice == '2':
print(a, "-", b, "=",
private void jEliminarActionPerformed(java.awt.event.ActionEvent evt) {
try {
PreparedStatement pps = conexion.prepareStatement("delete from articulos where codigo_articulo='"+txtCodigo.getText()+"'");
pps.executeUpdate();
JOptionPane.showMessageDialog(null, "Dato eliminado");
} catch (SQLException ex) {
Logger.getLogger(GestionarArticulos.class.getName()).log(Level.SEVERE, null, ex);
}
}
void createTicket() {
//code
}
Script
def menu():
print("1. Sumar")
print("2. Restar")
print("3. Multiplicar")
print("4. Dividir")
print("5. Salir")
menu()
Script
function createAppointment(){
let appt = new Appointment();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String cod=txtcod.getText();
try {
cts=cn.prepareCall("{call eliminarcliente(?)}");
cts.setString(1, cod);
int rpta=cts.executeUpdate();
if(rpta==1){
JOptionPane.showMessageDialog(this,"Cliente Eliminado correctamente!!","Aviso",JOptionPane.INFORMATION_MESSAGE);
BOTONES();
DESABILITAR();
limpiar();
cargar();
}else {
JOptionPane.showMessageDialog(this, "Cliente no Eliminado", "Aviso", JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException | HeadlessException e) {JOptionPane.showMessageDialog(this, e.toString
public Cliente getCliente(int id) {
Cliente cliente = null;
try {
String query = "SELECT * FROM clientes WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
cliente = new Cliente();
cliente.setId(rs.getInt("id"));
cliente.setNombre(rs.getString("nombre"));
cliente.setApellidos(rs.getString("apellidos"));
cliente.setEmail(rs.getString("email"));
cliente.setTelefono(rs.getString("telefono"));
cliente.setCalle(rs.getString("calle"));
cliente.setNumero(rs.getInt("numero"));
cliente.setPiso(rs.getString("piso"));
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Ejercicio 3
*
* @author Arturo
*/
public class Ejercicio03 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numero1, numero2, suma;
System.out.println("Introduce el primer número: ");
numero1 = Integer.parseInt(br.readLine());
System.out.println("Introduce el segundo número: ");
numero2 = Integer.parseInt(br.readLine());
suma = numero1 + numero2;
System.out.println("La suma de los números es: " + suma);
} catch (Exception e) {
System.out.println("Se ha producido un error:
//code here
Script
def saludo(nombre):
print(f'hola {nombre}')
saludo('Javier')
Script
function sum(a, b) {
return a + b;
}
function sum(a, b = 0) {
return a + b;
}
Script
function clear() {
var txtBox = document.getElementById("txt_nombre");
txtBox.value = "";
var txtBox = document.getElementById("txt_apellido");
txtBox.value = "";
var txtBox = document.getElementById("txt_edad");
txtBox.value = "";
var txtBox = document.getElementById("txt_email");
txtBox.value = "";
var txtBox = document.getElementById("txt_fecha");
txtBox.value = "";
var txtBox = document.getElementById("txt_celular");
txtBox.value = "";
var txtBox = document.getElementById("txt_direccion");
txtBox.value = "
public int sumar(int a, int b) {
return a + b;
}
Script
function default(x, y = 9){
return x + y
}
default(1)
public void actionPerformed(ActionEvent arg0) {
//Cargo datos de la base de datos
String sql = "SELECT * FROM empleados";
try{
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost/bd_recurso_humano", "root", "");
PreparedStatement pst = cn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
//Limpiar
cmbx_nombre.removeAllItems();
while(rs.next()){
cmbx_nombre.addItem(rs.getString("nombre_empleado"));
}
}catch (Exception e){
}
}
Script
function add(a, b){
return a + b
};
add(1, 2)
Script
function showMenu(){
var menu = document.createElement('p');
menu.innerHTML = "Help me";
document.getElementById('menu').appendChild(menu);
}
private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/bd_proyecto", "root", "");
PreparedStatement pst=cn.prepareStatement("delete from usuarios where codigo = ?");
pst.setString(1, jTextFieldCodigo.getText().trim());
pst.executeUpdate();
jTextFieldCodigo.setText("");
jTextFieldNombre.setText("");
jTextFieldDireccion.setText("");
jTextFieldTelefono.setText("");
jTextFieldCorreo.setText("");
JOptionPane.showMessageDialog(null, "Registro Eliminado.");
}catch(Exception e){
System.out.print(e.getMessage());
public class Soporte {
public static void main(String[] args) {
crearCita();
}
public static void crearCita() {
int opcion = 0;
if (opcion) {
return "El usuario ingreso la opcion"
}
}
}
public class Hello
{
public static void main(String[] args)
{
System.out.println("Enter your name: ");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
System.out.println("Welcome "+name);
}
}
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int fila = tbEstudiantes.getSelectedRow();
String cod = "";
cod = tbEstudiantes.getValueAt(fila, 0).toString();
if (fila >= 0) {
try {
PreparedStatement pps = cn.prepareStatement("DELETE FROM estudiantes WHERE cod_est ='" + cod + "'");
pps.executeUpdate();
JOptionPane.showMessageDialog(null, "Dato Eliminado");
mostrardatos("");
} catch (SQLException ex) {
Logger.getLogger(Interfaz.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Script
function menu(button, customer_name, customer_email, customer_problem){
if(button == 'support'){
retrun 'Hi ' + customer_name + ' please send us and email at '+ customer_email + ' with your problem ' + customer_problem
}
}
menu('support', 'Peter', 'peter@example.com', 'My computer is broken')
private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {
int selectedIndex = model.getSelectedIndex();
switch (selectedIndex) {
case 0:
model.addElement("Item6");
model.addElement("Item7");
model.addElement("Item8");
model.addElement("Item9");
model.addElement("Item10");
break;
case 1:
model.addElement("Item11");
model.addElement("Item12");
model.addElement("Item13");
model.addElement("Item14");
model.addElement("Item15");
break;
case 2:
model.addElement("Item16");
model.addElement("Item17");
model.addElement("Item18");
model.addElement("Item19");
model.addElement("Item20");
break;
case 3:
model.addElement("Item21");
model.addElement("Item22
Script
def menu():
choice = int(input('Selecciona una opción: \n1. Sumar\n2. Restar\n3. Multiplicar\n4. Dividir\n5. Salir\n'))
return choice
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
def calculate(choice, a, b):
if choice == 1:
return add(a, b)
elif choice == 2:
return sub(a, b)
elif choice == 3:
return mul(a, b)
elif choice == 4:
return div(a, b)
while True:
choice = menu()
if choice != 5:
a = int(input('Ingresa el primer valor: '))
b = int(input('Ingresa el seg
private void registrarActionPerformed(java.awt.event.ActionEvent evt) {
if (registrar.getText().equals("Registrar")) {
modeloRegistro= new DefaultComboBoxModel(modelo);
jComboBox1.setModel(modeloRegistro);
registrar.setText("Guardar");
} else {
modeloRegistro= new DefaultComboBoxModel(modelo);
jComboBox1.setModel(modeloRegistro);
registrar.setText("Registrar");
}
}
import javax.swing.JOptionPane;
public class Menu {
public static void main(String[] args) {
int opcion = 0;
do {
try {
opcion = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Sumar\n2. Restar\n3. Multiplicar\n4. Dividir\n0. Salir", " MENU DE OPCIONES ", JOptionPane.QUESTION_MESSAGE));
switch (opcion){
case 0:
break;
case 1:
JOptionPane.showMessageDialog(null,"La suma es: " + sumar());
break;
case 2:
JOptionPane.showMessageDialog(null,"La resta es: " + restar());
break;
case 3:
JOptionPane.showMessageDialog(null,"La multiplicacion es: " + multiplicar());
break;
case 4:
JOption
double a = Double.parseDouble(JOptionPane.showInputDialog("Introduce el primer número"));
double b = Double.parseDouble(JOptionPane.showInputDialog("Introduce el segundo número"));
if (opc == 1) {
resultado = a + b;
}
public static String getDayOfWeek(int dayNumber) {
String dayOfWeek = "";
if(dayNumber == 1) {
dayOfWeek = "Monday";
} else if(dayNumber == 2) {
dayOfWeek = "Tuesday";
} else if(dayNumber == 3) {
dayOfWeek = "Wednesday";
} else if(dayNumber == 4) {
dayOfWeek = "Thursday";
} else if(dayNumber == 5) {
dayOfWeek = "Friday";
} else if(dayNumber == 6) {
dayOfWeek = "Saturday";
} else if(dayNumber == 7) {
dayOfWeek = "Sunday";
} else {
dayOfWeek = "Weekday";
}
return dayOfWeek;
}
Script
function add(a, b) {
return a + b
}
add(1, 2)
public List<Employees> getEmployees() {
final String query = "select * from employees";
List<Employees> employees = new ArrayList<>();
try (Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(query);
ResultSet rs = stmt.executeQuery();) {
while (rs.next()) {
Employee employee = new Employee(rs.getString("name"), rs.getString("lastname"));
employees.add(employee);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return employees;
}
Script
#!/bin/bash
# Author: [YOUR NAME]
clear
echo "------------------------------------------"
echo " Bienvenido a la sesion de soporte tecnico "
echo "------------------------------------------"
echo " [1] - Crear una cita "
echo " [2] - Ver citas pendientes "
echo " [3] - Salir "
echo "------------------------------------------"
read -p " Enter your choice [1-3] : " choice
case $choice in
1)
" Cita creada"
sleep 2
;;
2)
" Cita pendiente"
sleep 2
;;
3)
exit 0
;;
*)
echo " Incorrect choice"
sleep 2
;;
esac
Script
function deleteData(){
// Delete the data
}
Generate
More than just a code generator. A tool that helps you with a wide range of tasks. All in one place.
Function from Description
Text Description to SQL Command
Translate Languages
Generate HTML from Description
Code to Explanation
Fix invalid Code
Get Test for Code
Class from Description
Regex from Description
Regex to Explanation
Git Command from Description
Linux Command
Function from Docstring
Add typing to code
Get Language from Code
Time complexity
CSS from Description
Meta Tags from Description
− sponsored −