PROGRAMAS

Los primeros 12 programas presentan los diferentes tipos de datos y operaciones con JAVA, estos los edite en el NOTEPAD y fueron compilados y corridos primero desde MS-DOS y despúes utilizando NetBeans.

Programa sencillo para aprender a escribir mensajes en la pantalla
 
import java.io.*;
public class Hello
{
    public static void main(String[] args) throws IOException
    {
    InputStreamReader reader=new
    InputStreamReader(System.in);
        BufferedReader Input=new BufferedReader (reader);
    System.out.println("Introdece tu nombre: ");
    String name=Input.readLine();
    System.out.println("Hello "+name+"!");
    }
}

_________________________________________________________________________________
Programa para manejar los diferentes tipos de datos numéricos
 public class Ejemplo_1
{
    public static void main(String[] args)
    {
      int i=9,k;//Se declara una constante i=9 y la variable K de tipo int
      float j=47.9F;//indicacion de que se trata de una constante flotante, si no sería doble
      System.out.println("i: "+i+"   j: "+j);
      k=(int)j;//empleo de un cast una constante de jerarquía superior se almacena en una de tipo inferior, perdiendo parte de la información
      System.out.println("j: "+j+"   k: "+k);
      j=k;//no necesita cast
      System.out.println("j: "+j+"   k: "+k);
      float m=2.3F;//float m=2.3;provocaría un error
      System.out.println("m: "+m);
    }
}

 ______________________________________________________________________________
Programa para calcular el área de un círculo, y poder practicar operaciones matemáticas con diferentes tipos de variables.

import java.io.*;
public class area
{
        public static void main(String[] args) throws IOException
        {
                InputStreamReader reader= new InputStreamReader(System.in);
                BufferedReader Input=new BufferedReader (reader);
                System.out.println("Introduce el radio del círculo: ");
                String radio=Input.readLine();
                Double x=new Double(radio);
                Double r=x.doubleValue();
                Double a=3.1415*r*r;
                System.out.println("El  rea de un círculo de radio "+r+"es:"+ a);
         }
}
___________________________________________________________________________________
Programa para observar el resultado de los operadores ++ y --


public class Ejemplo_2
{
//Manejo de operadores incremento y decremento ++ --
    public static void main (String[] args)
    {
      int i=1;
      prt("i: "+i);
      prt("++1: "+ ++i);
    //Pre-incremento, primero incrementa y luego lo muestra en pantalla
      prt("i++: "+ i++);
    //Post-incremento, primero muestra el 2 y luego incrementa a 3
      prt("i: "+ i);//muestra el 3
      prt("--i: "+ --i);
    //Pre-decremento, primero decrementa i y luego lo muestra
      prt("i-- : "+ i--);
    //Post-decremento, primero muestra i y luego decrementa su valor en 1
      prt("i : "+i);//Ahora i vale 1
    }
    static void prt(String s)
    {
      System.out.println(s);
    //Estas últimas instrucciones son para utilizar prt que nos permite mostrar cadenas de caracteres
    //en pantalla ahorrandonos el System.out.println
    }
}
__________________________________________________________________________________
Programa para observar la utilización de la clase Math, utilizando algunas funciones trigonometricas y potencias.


public class Ejemplo_3
{
//Ejemplo del método de la clase Math
    public static void main(String[] args)
    {
      int i=45, j=2;
      //Imprime en la pantalla el Seno y el Coseno de 45
      prt("i: "+ i + "  Coseno de i: " + Math.cos(i));
      prt("i: "+ i + "  Seno de i: " + Math.sin(i));
      prt("j: "+ j + " i: " + i + "  i^j (i elevada a la j): "+ Math.pow(i,j));
    }
    static void prt(String s)
    {
      System.out.println(s);
    }
}
  
_________________________________________________________________________________
Programa para observar operadores binarios.

import java.util.*;
public class Ejemplo_4
{
    public static void main(String[] args)
    {
//Creacion de un objeto tipo Random almacenando un puntero a el en la variable rand
      Random rand=new Random();
//Se generan dos números aleatorio entre 0 y 100
      int i= rand.nextInt() % 100;
      int j= rand.nextInt() % 100;
      prt("i = "+ i);
      prt("j = "+ j);
//Imprime diversas operaciones binarias sobre i y j, junto con su resultado
      prt("i = " + i+ "  j = "+j);
      prt("i > j es "+ (i>j));
      prt("i < j es "+ (i<j));
      prt("i >= j es " + (i>=j));
      prt("i <= j es " + (i<=j));
      prt("i == j es " + (i==j));
      prt("i != j es " + (i!=j));
      prt("(i < 10) && (j < 10) es " + ((i<10)&&(j<10)));
      prt("(i < 10) || (j < 10) es " + ((i<10)||(j<10)));
    }
    static void prt(String s)
    {
      System.out.println(s);
    }
}

___________________________________________________________________________________
Programa para observar el resultado de los operadores aplicados a variables de tipo String.

public class Ejemplo_5
{
    public static void main(String[] args)
    {
      String saludo= "Hola";
      String saludo2= "hola";
      int n=5;
//Imprime en pantalla la subcadena formada por los caracteres 0 hasta 2 sin incluir el último
      prt("saludo ="+ saludo + "substring (0,2) :");
      prt(saludo.substring(0,2));
      prt(saludo + " " + n);
      prt("Imprime el resultado del test de igualdad entre Hola y hola");
      prt("saludo == saludo2 " + saludo.equals(saludo2));
    }
    static void prt(String s)
    {
      System.out.println(s);
    }
}

___________________________________________________________________________________
Programa para observar el manejo de vectores, mediante el manejo de un vector de tamaño igual a 10.
public class Ejemplo_5a
{
    public static void main(String[] args)
    {
      int[] edades = new int[10];
      for (int i=0; i<10; i++)
        {
        edades[i]=i*2;
        System.out.println("Elemento "+ i + "  tiene almacenada una edad igual a: "+edades[i]);
        }
      int sum = 0;
      for (int i=0; i<10; i++)
        {
        sum=sum+edades[i];
        }
      System.out.println("Suma de edades igual a: "+sum);
    }
}  
____________________________________________________________________________
Programa para observar como podemos crear listas de datos y manejar a sus elementos mediante su dirección dentro del vector.


public class Ejemplo_5b
{
//Definimos un tipo enumerado fuera del main y fuera de cualquier método
public enum Semana {LUNES, MARTES, MIERCOLES, JUEVES, VIERNES, SABADO, DOMINGO};
    public static void main (String[] args)
    {
//Definimos la variable hoy de tipo Semana y le asignamos un valor
      Semana hoy=Semana.MARTES;
//Hacemos una comparación, si la variable hoy es igual a SABADO o DOMINGO
//despliega el mensaje "Hoy no se trabaja"
      if (hoy == Semana.SABADO || hoy == Semana.DOMINGO)
      {
        System.out.println("HOY NO SE TRABAJA");
      }    else
            {
              System.out.println("HOY SE TRABAJA");
            }
    }
}
_________________________________________________________________________________
Programa para el funcionamiento de IF- ELSE

public class Ejemplo_6
{
//La siguiente instrucción test(int a, int b) devolverá
// un -1 si a<b, +1 si a>b y 0 si a==b
    static int test (int val, int val2)
    {
      int result=0;
      if(val > val2)
        result= +1;
      else if (val < val2)
        result= -1;
      else
        result= 0;
      return result;
    }
    public static void main(String[] args)
    {
      System.out.println("Test (10,5) "+test(10,5));
      System.out.println("Test (5,10) "+test(5,10));
      System.out.println("Test (5,5) "+test(5,5));
    }
}
__________________________________________________________________________________
Programa para observar el manejo de la instrucción CASE

public class Ejemplo_7
{
//Ejemplo de for con switch
    public static void main(String[] args)
    {
      for(int i=0; i<100;i++)
      {
      char c= (char)(Math.random()*26 + 'a');
      System.out.print(c + " : ");
      switch (c)
        {
          case 'a':
          case 'e':
          case 'i':
          case 'o':
          case 'u':
//Si el carácter es a, e, i, o, ó u se imprimen
              System.out.println("vocal: "+c);
              break;
          default:
//Si no era vocal, imprimimos consonante
              System.out.println("consonante: "+c);
        }
      }
    }
}
__________________________________________________________________________________
Programa para observar el resultado de la instrucción WHILE

public class Ejemplo_8
{
    public static void main(String[] args)
    {
      double r=0;
//Mientras r<0.99 se ejecuta el cuerpo del bucle
      while (r<0.99)
        {
          r=Math.random();
          System.out.println("r es menor que 0.99, r="+r);
        }
      System.out.println("Aquí se detuvo porque r = "+ r);
    }
}
__________________________________________________________________________________
Programa para observar el funcionamiento de la instrucción DO-WHILE

public class Ejemplo_9
{
    public static void main(String[] args)
    {
      double r;
//Igual al Ejemplo_8 pero ahora la condición esta al final
      do
        {
          r=Math.random();
          System.out.println(r);
        }
      while (r<0.99);
      System.out.println("Aquí se detiene porque r = "+ r);
    }
}
__________________________________________________________________________________
Programa para observar el funcionamiento de la instrucción FOR

public class Ejemplo_10
{
    public static void main(String[] args)
    {
//Aquí definimos el array que tendra los elementos de la iteracción
      int array[] = new int[10];
      int suma=0, contador=0;
//Damos valores a la matriz por medio de este bucle
      for (int i=0; i< array.length; i++)
        {
          array[i]=2*i;
          System.out.println("array ["+i+"]"+" = "+ array[i]);
        }
      for (int e: array)
        {
          suma = suma + e;
            System.out.println("Valores de suma = "+ suma);
        }
      System.out.println("Al final suma = "+suma);
    }
}
___________________________________________________________________________________
Programa para observar las instrucciones FOR, IF y WHILE

public class Ejemplo_11
{
    public static void main(String[] args)
    {
      for (int i=0; i< 100; i++)
        {
          if (i== 74) break; //Se sale del bucle cuando i=74
          if (i%9 != 0) continue;//Si i es divisible entre 9 se imprime en pantalla
          System.out.println("i = "+i);
        }
      int i=0;
      while (true)
        {
          i++;
          if(i == 120) break;
            System.out.println("Valores i = "+ i);
        }
    }
}
____________________________________________________________________________________
Programa para convertir dolares a pesos.

import java.io.*;
public class Conversion
{
    public static void main(String[] args) throws IOException
    {
        InputStreamReader reader= new InputStreamReader (System.in);
        BufferedReader Input= new BufferedReader(reader);
        System.out.println("Introduce la cantidad de dolares");
        String cantidad_dolares = Input.readLine();
        Double x = new Double(cantidad_dolares);
        r=x.doubleValue();
       
        InputStreamReader reader= new InputStreamReader (System.in);
        BufferedReader Input= new BufferedReader(reader);
        System.out.println("Introduce el valor del dolar");
        String valor_dolar = Input.readLine();
        Double y = new Double(valor_dolar);
        s= y.doubleValue();
        Double resultado = x*y;
        System.out.println("El valor en pesos es de "+ resultado);
    }
}
____________________________________________________________________________________
Programa que pide dos numeros, los suma y entrega el resultado.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package addition;
import java.util.Scanner;
/**
 *
 * @author Xochitl Meza
 */
public class Addition
{
    //empieza la ejecución del método principal
    public static void main(String[] args)
    {
      
        // Creación del Scanner
        Scanner input = new Scanner (System.in);
      
        int number1;//primer núnero a sumar
        int number2;//segundo número a sumar
        int sum;//resultado de la suma de los dos números
        System.out.println("Introduce el primer entero:");
        number1 = input.nextInt();//lee el primer número entero
      
        System.out.println("Introduce el segundo número entero:");
        number2 = input.nextInt();//lee el segundo número entero
      
        sum = number1 + number2;
      
        System.out.println("La suma es %d\n" + sum);//muestra el resultado de la suma
      
              
    }// fin del método principal
}//fin de la clase Addition
____________________________________________________________________________________
Programa para almacenar y cambiar 20 números en un arreglo unidimensional

package matriz_20;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Xochitl Meza Vázquez

 */
public class Matriz_20
{
    public static void main(String[] args) throws IOException
    {
        int[] dato = new int[20];
        for (int i=0; i<20; i++)
        {
            InputStreamReader reader = new
                    InputStreamReader (System.in);
            BufferedReader Input=new BufferedReader (reader);
            System.out.println("Introduce el dato "+ i+":");
            String elemento =Input.readLine();
            Integer x = new Integer(elemento);
            dato[i]=x;
        }
        InputStreamReader reader = new
                    InputStreamReader (System.in);
        BufferedReader Input=new BufferedReader (reader);
        System.out.println("Los datos capturados fueron:");
        for (int i=0; i<20; i++)
        {
            System.out.print(dato[i]+"  ");
        }
        System.out.println("\nQue dato quieres cambiar: ");
        String elemento =Input.readLine();
        Integer x = new Integer(elemento);
        System.out.println("El dato["+x+"]"+ " actual es:"+ dato[x]);
        System.out.println("\nIntroduce el nuevo valor de dato["+x+"]"+ ":");
        String elemento2 =Input.readLine();
        Integer x2 = new Integer(elemento2);
        dato[x]=x2;
        System.out.println("\nLos datos nuevos datos de la matriz son:");
        for (int i=0; i<20; i++)
        {
            System.out.print(dato[i]+"  ");
        }   
 
  
        }
    }

____________________________________________________________________________________
Igual al anterior pero presenta los numeros de forma diferente
package matriz_modificacion1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 *
 * @author X
 */
public class Matriz_modificacion1 {
    public static void main(String[] args) throws IOException
    {
        int[] dato = new int[20];
        for (int i=0; i<20; i++)
        {
            InputStreamReader reader = new
                    InputStreamReader (System.in);
            BufferedReader Input=new BufferedReader (reader);
            System.out.println("Introduce el dato "+ i+":");
            String elemento =Input.readLine();
            Integer x = new Integer(elemento);
            dato[i]=x;
        }
        InputStreamReader reader = new
                    InputStreamReader (System.in);
        BufferedReader Input=new BufferedReader (reader);
        System.out.println("Los datos capturados fueron:");
        for (int i=0; i<20; i++)
        {
            System.out.print("\n M["+i+"]: "+dato[i]);
        }
        System.out.println("\nQue dato quieres borrar: ");
        String elemento =Input.readLine();
        Integer x = new Integer(elemento);
        System.out.println("El dato["+x+"]"+ " actual es:"+ dato[x]);
        dato[x]=0;
        System.out.println("\nLos datos nuevos datos de la matriz son:");
        for (int i=0; i<20; i++)
        {
            System.out.print("\n M["+i+"]: "+dato[i]);
        }   
 
  
        }
    }
___________________________________________________________________________________
Programa para almacenar 20 nombre en un arreglo unidimensional
package matriz_nombres;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Xochitl Meza Vázquez

 */
public class Matriz_nombres
{
    public static void main(String[] args) throws IOException
    {
        String[] dato = new String[20];
        for (int i=0; i<20; i++)
        {
            InputStreamReader reader = new
                    InputStreamReader (System.in);
            BufferedReader Input=new BufferedReader (reader);
            System.out.println("Introduce el dato "+ i+":");
            String nombre =Input.readLine();
            dato[i]=nombre;
        }
        InputStreamReader reader = new
                    InputStreamReader (System.in);
        BufferedReader Input=new BufferedReader (reader);
        System.out.println("Los datos capturados fueron:");
        for (int i=0; i<20; i++)
        {
            System.out.print(dato[i]+"  ");
        }
        System.out.println("\nQue dato quieres cambiar: ");
        String elemento =Input.readLine();
        Integer x = new Integer(elemento);
        System.out.println("El dato["+x+"]"+ " actual es:"+ dato[x]);
        System.out.println("\nIntroduce el nuevo valor de dato["+x+"]"+ ":");
        String elemento2 =Input.readLine();
        dato[x]=elemento2;
        System.out.println("\nLos datos nuevos datos de la matriz son:");
        for (int i=0; i<20; i++)
        {
            System.out.print(dato[i]+"  ");
        }   
 
  
        }
}
___________________________________________________________________________________
Programa para calcular si un número introducido por el teclado es primo
package numprimo;

/**
 *17.10.11
 * @author Xochitl
 */
import java.io.*;
public class NumPrimo
{
    public static void main(String args[]) throws IOException
    {
        InputStreamReader isr = new InputStreamReader (System.in);
        BufferedReader br = new BufferedReader (isr);
        String cadena;
        try
        {
            System.out.println("Dame un numero entero: ");
            cadena = br.readLine();
            int i= Integer.parseInt(cadena);
            boolean primo = true;
            int raiz2 = (int)Math.sqrt(i);
            for (int d=2; primo && d<= raiz2; d++){
                if (i%d == 0)
                    primo = false;
                if (i==0 || !primo)   System.out.println("El "+ i +"  es compuesto");
              
                else
                    System.out.println("El "+ i +"es primo");
             }
        }
        catch (Exception e)
        {
            System.out.print("Cualquier tipo de error");
        } 
    }             
}
____________________________________________________________________________________
Programa para practicar la instrucción FOR mostrando una tabla de multiplicaciones.
package tabla;

/**
 *
 * @author XOCHITL
 */
import java.io.*;
public class Tabla {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String cadena;
        int n=0,i=0;
        System.out.println("Escribe un número: ");
        cadena = br.readLine();
        n= Integer.parseInt(cadena);
        for(i=1; i<=10 ;i++ )
            System.out.println(i+" * "+ n + " = "+ i*n);
     }
}

No hay comentarios:

Publicar un comentario