domingo, 10 de diciembre de 2017

Crear una Linea en JAVA Netbens "Plano cartesiano"


Crear una Linea en JAVA Netbens "Plano cartesiano"













CODIGO DEL PROGRAMA









-

import java.awt.Graphics;
import javax.swing.JPanel;


public class Linea extends javax.swing.JFrame {
public class Dibujo2D extends JPanel{
public Dibujo2D(){

}
@Override
protected void paintComponent(Graphics g){
int x1,x2, y1, y2;
x1=(int)Double.parseDouble(X1.getText());
y1=(int)Double.parseDouble(Y1.getText());
x2=(int)Double.parseDouble(X2.getText());
y2=(int)Double.parseDouble(Y2.getText());
g.drawLine(x1, y1, x2, y2);
}
}
 

    public Linea() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                       
    private void initComponents() {

        panel11 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        X1 = new javax.swing.JTextField();
        X2 = new javax.swing.JTextField();
        Y1 = new javax.swing.JTextField();
        Y2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panel11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));

        javax.swing.GroupLayout panel11Layout = new javax.swing.GroupLayout(panel11);
        panel11.setLayout(panel11Layout);
        panel11Layout.setHorizontalGroup(
            panel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );
        panel11Layout.setVerticalGroup(
            panel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 188, Short.MAX_VALUE)
        );

        jLabel1.setText("x1");

        jLabel2.setText("x2");

        jLabel3.setText("y1");

        jLabel4.setText("y2");

        jButton1.setText("Dibuja");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        X2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                X2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(X1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Y1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(Y2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(X2))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 41, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(panel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(X1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(X2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(Y1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Y2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(41, 41, 41)
                        .addComponent(jButton1)))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        dibujar();// TODO add your handling code here:
    }                                     

    private void X2ActionPerformed(java.awt.event.ActionEvent evt) {                                 
        // TODO add your handling code here:
    }                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Linea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Linea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Linea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Linea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Linea().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.JTextField X1;
    private javax.swing.JTextField X2;
    private javax.swing.JTextField Y1;
    private javax.swing.JTextField Y2;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel panel11;
    // End of variables declaration                 
private void dibujar(){
Linea.Dibujo2D dibuj=new Linea.Dibujo2D() ;
dibuj.setBounds(50,100,1000,1000);
dibuj.setOpaque(false);
panel11.add(dibuj);
panel11.repaint();
}
}

sábado, 9 de diciembre de 2017

Ecuación de segundo grado

Pedir los coeficientes de una ecuación se 2º grado, y muestre sus soluciones . Si no existen indicarlo.

formulas:













import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaApplication1 {




    public static void main(String[] args) throws IOException {
     
        double a2,b2, d,x1 = 0,x2;
     
       System.out.println("Introduzaca primer coheficiente a:");
       System.out.println("Introduzaca primer coheficiente b:");
       System.out.println("Introduzaca primer coheficiente c:");
     
        BufferedReader Entrada = new BufferedReader(new InputStreamReader(System.in));
     
       String a=Entrada.readLine();
        a2=Double.parseDouble(a);
     
        String b=Entrada.readLine();
        b2 = Double.parseDouble(b);
     
        String c=Entrada.readLine();
        double c2 = Double.parseDouble(c);
     
     
       
      // calculamos el determinante
 d=((b2*b2)-4*a2*c2);
 if(d<0)
 System.out.println("No existen soluciones reales");

 else
 // queda confirmar que a sea distinto de 0.
// si a=0 nos encontramos una división por cero.

 x1=(-b2+Math.sqrt(d))/(2*a2);
  x2=(-b2 - Math.sqrt(d))/(2* a2);

    System.out.println(  "Solución: "+ x1);
 System.out.println("Solución: " + x2);


    }
   }
-------------------------------------------------------------------------------------------------------------------
run:
Introduzaca primer coheficiente a:
Introduzaca primer coheficiente b:
Introduzaca primer coheficiente c:
2
5
3
Solución: -1.0
Solución: -1.5
BUILD SUCCESSFUL (total time: 11 seconds)

sábado, 28 de octubre de 2017

Lógica sucesión de números

Dada la siguiente sucesión de números: 2, 4, 8, 6, 36, 72, 70, 4900, 9800,... mediante el uso de funciones, mostrar en pantalla los términos de esta serie y calcular la suma de N (N se indica por teclado) elementos, es decir, SUMA=2+4+8+6+.....
EXPLICACION DEL PROGRAMA: El programa calcula la suma de la serie anterior para n terminos. Para ello, genera cada uno de los valores de dicha serie hasta el limite ingresado por el usuario. La logica que sigue la serie es de elevar al cuadrado, multiplicar por dos y restar dos.
😐😉












import java.io.*;

public class a9 {
public static void main(String args[])throws IOException {
BufferedReader in; int s=0,a=2;
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Introduzca el limite N");
int n=Integer.parseInt(in.readLine());
for(int i=0;i<n;) {
 System.out.println(a);
 s=s+a; i++; a=op1(a);
 if(i==n)
break;
 else {
System.out.println(a);
 s=s+a;
a=op2(a); i++;
 }
 if(i==n) break;
else {
System.out.println(a);
 s=s+a;
 a=op3(a); i++; }
 }
 System.out.println("La suma de la serie es: "+s);
}
 public static int op1 (int b) {
return b*b;
}
public static int op2 (int b) {
return b*2;
}
 public static int op3 (int b) {
return b-2;}
}

--------------------Configuration: <Default>--------------------
Introduzca el limite N
4
2
4
8
6
La suma de la serie es: 20

Process completed.

miércoles, 9 de noviembre de 2016

Merge sort

Merge sort

public class MergeSort { 

private int[] array; 
private int[] tempMergArr; 
private int length; 

public static void main(String a[]) { 

int[] inputArr = { 32, 27, 51, 89, 1, 98, 9, 28, 65, 0 }; 
MergeSort mms = new MergeSort(); 
mms.sort(inputArr); 

for (int i : inputArr) { 

System.out.print(i); 
System.out.print(" "); 




public void sort(int inputArr[]) { 

this.array = inputArr; 
this.length = inputArr.length; 
this.tempMergArr = new int[length]; 
doMergeSort(0, length - 1); 



private void doMergeSort(int lowerIndex, int higherIndex) { 

if (lowerIndex < higherIndex) { 

int middle = lowerIndex + (higherIndex - lowerIndex) / 2; 
// Below step sorts the left side of the array 
doMergeSort(lowerIndex, middle); 
// Below step sorts the right side of the array 
doMergeSort(middle + 1, higherIndex); 
// Now merge both sides 
mergeParts(lowerIndex, middle, higherIndex); 




private void mergeParts(int lowerIndex, int middle, int higherIndex) { 

for (int i = lowerIndex; i <= higherIndex; i++) { 

tempMergArr[i] = array[i]; 



int i = lowerIndex; 
int j = middle + 1; 
int k = lowerIndex; 

while (i <= middle && j <= higherIndex) { 

if (tempMergArr[i] <= tempMergArr[j]) { 

array[k] = tempMergArr[i]; 
i++; 

} else { 

array[k] = tempMergArr[j]; 
j++; 



k++; 


while (i <= middle) { 

array[k] = tempMergArr[i]; 
k++; 
i++; 




}










--------------------Configuration: <Default>--------------------
0 1 9 27 28 32 51 65 89 98 

Process completed.

martes, 8 de noviembre de 2016

Shell Sort

Method Shell Sort

public class ShellSort {

private long[] data;
private int len;

public ShellSort(int max) {

data = new long[max];
len = 0;

}

public void insert(long value) {

data[len] = value;
len++;

}

public void display() {

for (int j = 0; j < len; j++) {

System.out.print(data[j] + " ");

}

System.out.println("");
}

public void shellSort() {

int inner, outer;
long temp;
// find initial value of h

int h = 1;

while (h <= len / 3) {

h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
}

while (h > 0) // decreasing h, until h=1
{
// h-sort the file
for (outer = h; outer < len; outer++) {

temp = data[outer];
inner = outer;

// one subpass (eg 0, 4, 8)
while (inner > h - 1 && data[inner - h] >= temp) {

data[inner] = data[inner - h];
inner -= h;

}

data[inner] = temp;
}

h = (h - 1) / 3; // decrease h
}
}

public static void main(String[] args) {

int maxSize = 10;
ShellSort arr = new ShellSort(maxSize);

for (int j = 0; j < maxSize; j++) {

long n = (int) (java.lang.Math.random() * 99);
arr.insert(n);

}

System.out.print("Unsorted List:\n");
arr.display();

arr.shellSort();

System.out.print("-------------------------\n");
System.out.print("Sorted List:\n");
arr.display();
}
}








--------------------Configuration: <Default>--------------------
Unsorted List:
30 8 86 63 89 38 71 94 79 64 
-------------------------
Sorted List:
8 30 38 63 64 71 79 86 89 94 

Process completed.

lunes, 7 de noviembre de 2016

Method Heap Sort (Método de ordenamiento Heap Sort)

Método de ordenamiento Heap Sort








public class HeapSort { 

public static void main(String a[]) { 

int i; 
int arr[] = { 1, 3, 4, 5, 2 }; 

System.out.println("\nHeap Sort\n---------------"); 
System.out.println("\nUnsorted Array\n---------------"); 

for (i = 0; i < arr.length; i++){ 

System.out.print(" " + arr[i]); 



for (i = arr.length; i > 1; i--) { 

fnSortHeap(arr, i - 1); 



System.out.println("\n\nSorted array\n---------------"); 

for (i = 0; i < arr.length; i++){ 

System.out.print(" " + arr[i]); 





public static void fnSortHeap(int array[], int arr_ubound) { 

int i, o; 
int lChild, rChild, mChild, root, temp; 

root = (arr_ubound - 1) / 2; 

for (o = root; o >= 0; o--) { 

for (i = root; i >= 0; i--) { 

lChild = (2 * i) + 1; 
rChild = (2 * i) + 2; 

if ((lChild <= arr_ubound) && (rChild <= arr_ubound)) { 

if (array[rChild] >= array[lChild]) 
mChild = rChild; 
else 
mChild = lChild; 

} else { 

if (rChild > arr_ubound) 
mChild = lChild; 
else 
mChild = rChild; 



if (array[i] < array[mChild]) { 

temp = array[i]; 
array[i] = array[mChild]; 
array[mChild] = temp; 





temp = array[0]; 
array[0] = array[arr_ubound]; 
array[arr_ubound] = temp; 
return; 


}

--------------------Configuration: <Default>--------------------

Heap Sort
---------------

Unsorted Array
---------------
 1 3 4 5 2

Sorted array
---------------
 1 2 3 4 5

Process completed.

domingo, 6 de noviembre de 2016

Method Quick Sort

Method Quick Sort

Selection sort





public class QuickSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println("Quick Sort\n\n");
System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++) {

System.out.print(array[i] + "  ");

}

System.out.println();

quick_srt(array, 0, array.length - 1);

System.out.print("\nValues after the sort:\n\n");

for (i = 0; i < array.length; i++) {

System.out.print(array[i] + "  ");

}

System.out.println();
}

public static void quick_srt(int array[], int low, int n) {

int lo = low;
int hi = n;

if (lo >= n) {

return;

}

int mid = array[(lo + hi) / 2];

while (lo < hi) {

while (lo < hi && array[lo] < mid) {

lo++;

}

while (lo < hi && array[hi] > mid) {

hi--;

}

if (lo < hi) {

int T = array[lo];
array[lo] = array[hi];
array[hi] = T;

}
}

if (hi < lo) {

int T = hi;
hi = lo;
lo = T;

}

quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);

}
}

--------------------Configuration: <Default>--------------------
Quick Sort


Values Before the sort:

12  9  4  99  120  1  3  10  13

Values after the sort:

1  3  4  9  10  12  13  99  120

Process completed.

sábado, 5 de noviembre de 2016

Ejemplo de método e ordenamiento por seleccion (Selection sort)


Selection sort





public class SelectionSortExample { 

public static int[] doSelectionSort(int[] arr) { 

for (int i = 0; i < arr.length - 1; i++) { 

int index = i; 

for (int j = i + 1; j < arr.length; j++) { 

if (arr[j] < arr[index]) { 

index = j; 



int smallerNumber = arr[index]; 
arr[index] = arr[i]; 
arr[i] = smallerNumber; 


return arr; 

public static void main(String a[]) { 

int[] arr1 = { 102, 34, 2, 56, 76, 5, 88, 42 }; 
int[] arr2 = doSelectionSort(arr1); 

for (int i : arr2) { 

System.out.print(i); 
System.out.print(", "); 


}

--------------------Configuration: <Default>--------------------
2, 5, 34, 42, 56, 76, 88, 102, 
Process completed.

viernes, 4 de noviembre de 2016

Metodo de ordenamiento Insertion sort

Insertion sort





public class InsertionSortExample {

static int step = 1;

    public static void main(String[] args) {
       
        int[] input = { 7, 21, 91, 43, 23, 17, 34, 9, 1 };
        insertionSort(input);
    }
   
    private static void printNumbers(int[] input) {
       
    System.out.println("Step "+step);
    System.out.println("-----------------------------");
    step++;
 
        for (int i = 0; i < input.length; i++) {
     
            System.out.print(input[i] + ", ");
         
        }
     
        System.out.println("\n");
    }

    public static void insertionSort(int array[]) {
 
        int n = array.length;
     
        for (int j = 1; j < n; j++) {
     
            int key = array[j];
            int i = j-1;
         
            while ( (i > -1) && ( array [i] > key ) ) {
         
                array [i+1] = array [i];
                i--;
             
            }
         
            array[i+1] = key;
            printNumbers(array);
        }
    }
}


--------------------Configuration: <Default>--------------------
Step 1
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,

Step 2
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,

Step 3
-----------------------------
7, 21, 43, 91, 23, 17, 34, 9, 1,

Step 4
-----------------------------
7, 21, 23, 43, 91, 17, 34, 9, 1,

Step 5
-----------------------------
7, 17, 21, 23, 43, 91, 34, 9, 1,

Step 6
-----------------------------
7, 17, 21, 23, 34, 43, 91, 9, 1,

Step 7
-----------------------------
7, 9, 17, 21, 23, 34, 43, 91, 1,

Step 8
-----------------------------
1, 7, 9, 17, 21, 23, 34, 43, 91,


Process completed.

martes, 1 de noviembre de 2016

Método de ordenamiento por intercambio (Exchange sort)

Exchange sort


Si alguien te hace volar, asegúrate de caer de pie cuando te suelte… ¡porque te soltará!








import java.util.*;
public class ExchangeSort
{
    public static void main(String[] args)
    {
        int[] array;
        int i, j, temp, size;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size of array");//Introduzca el tamaño de la matriz
        size = sc.nextInt();
        array = new int[size];

        System.out.println("Enter the elements of array : "); //Introduzca los elementos de la matriz
        for (i = 0; i < size; i++)
        {

            array[i] = sc.nextInt();
        }

        //Exchange sort , ordenacion de intercambio
        for (i = 0; i < (size - 1); i++)
        {
            for (j = (i + 1); j < size; j++)
            {
                if (array[i] > array[j])
                {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }

        System.out.println("Sorted Array is : "); //el vector ordenado es
        for (i = 0; i < size; i++)
        {
            System.out.print(array[i] + " ");
        }
    }
}

--------------------Configuration: <Default>--------------------
Enter the size of array
3
Enter the elements of array : 
2
5
7
Sorted Array is : 
2 5 7 
Process completed.