100% encontró este documento útil (1 voto)
610 vistas49 páginas

Ejercicios de Java

El documento presenta 9 problemas propuestos de Java con sus respectivas soluciones en código. Los problemas incluyen: 1) convertir de bolivianos a dólares y viceversa, 2) intercambiar el contenido de dos variables, 3) determinar si un año es bisiesto.

Cargado por

Natalia
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
100% encontró este documento útil (1 voto)
610 vistas49 páginas

Ejercicios de Java

El documento presenta 9 problemas propuestos de Java con sus respectivas soluciones en código. Los problemas incluyen: 1) convertir de bolivianos a dólares y viceversa, 2) intercambiar el contenido de dos variables, 3) determinar si un año es bisiesto.

Cargado por

Natalia
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 49

EJERCICIOS DE JAVA

PROBLEMAS PROPUESTOS
1. Escribir un programa que pida el tipo de cambio para que dada una
cantidad en Bolivianos y la convierta en Dolares y viceversa.
import java.io.*;
import java.text.DecimalFormat;
public class JavaApplication9 {
public static void main(String args[])throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int x=1,opc=5;
double z=0;
DecimalFormat df = new DecimalFormat("0.00");
while (opc>3||opc<1)
{
System.out.println("----------- Tipo de Cambio -----------");
System.out.println("1. Cantidad en Bolivianos y lo convierta en
Dolares");
System.out.println("2. Cantidad en Dolares y lo convierta en
Bolivianos");
System.out.println("3. Salir");
System.out.println("Ingresar su opcion:");
opc=Integer.parseInt(in.readLine());
}
switch (opc)
{
case 1:
System.out.println("Cantidad en Bolivianos y lo convierta en Dolares:
BOB/USD = 0.14448");
System.out.println("Ingresar la cantidad a convertir:");
x=Integer.parseInt(in.readLine());
z=0.14448 * x;
System.out.println("");
System.out.println("El Tipo de Moneda es:" + df.format(z)+" USD");
break;
case 2:
System.out.println("Cantidad en Dolares y lo convierta en Bolivianos:
USD/BOB = 6.9214");
System.out.println("Ingresar la cantidad a convertir:");
x=Integer.parseInt(in.readLine());
z=6.9214 * x;
System.out.println("");
System.out.println("El Tipo de Moneda es:" + df.format(z)+" BOB");
break;
case 3:
System.out.println("Usted salio");
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

break;
System.out.println("La hora en segundos: ");
System.out.println(hora + ":" + minutos + ":" + segundos);
}
}
2. Intercambiar el contenido de dos variables.
public class JavaApplication9
{
public static void main(String args[])
{
int A, B, AUX;
A = 5;
B = 6;
System.out.println("Valores iniciales: A = " + A + " B = " + B);
//instrucciones para hacer el intercambio
//se utiliza una variable auxiliar
AUX = A;
A = B;
B = AUX;
System.out.println("Valores intercambiados: A = " + A + " B = " +
B);
}
}
3. Determinar si un ao es bisiesto (verificar las condiciones)
import java.io.*;
import java.util.GregorianCalendar;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int anio=0;
System.out.println("Ingrese el Ao si es bisiesto");
anio=Integer.parseInt(in.readLine());
GregorianCalendar calendar = new GregorianCalendar();
if (calendar.isLeapYear(anio))
System.out.println("El ao es bisiesto");
else
System.out.println("El ao no es bisiesto");
}
}
4. Leer un par ordenado y determinar en qu cuadrante se encuentra.
import java.io.*;
import java.util.GregorianCalendar;
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

public class JavaApplication9


{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.print("valor de X: ");
int x = Integer.parseInt(br.readLine());
System.out.print("valor de Y: ");
int y = Integer.parseInt(br.readLine());
if (x == 0 || y == 0)
{
System.out.println("(x,y) no se encuentra en ninguno de los
cuadrantes.\n");
}
else
{
if (x > 0 && y > 0){
System.out.println("(x,y) se encuentra en el cuadrante I\n");
}
else if (x < 0 && y > 0)
{
System.out.println("(x,y) se encuentra en el cuadrante II\n");
}
else if (x < 0 && y < 0)
{
System.out.println("(x,y) se encuentra en el cuadrante III\n");
}
else if (x > 0 && y < 0)
{
System.out.println("(x,y) se encuentra en el cuadrante IV\n");
}
}
}
catch(Exception e)
{
System.err.println("\n\n" + e.toString() + "\n\n");
}
}
}
5. Convertir grados Centigrados en grados Fahrenheit
import java.io.*;
import java.util.GregorianCalendar;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
double grados;
try
{
System.out.println("Introduce el valor de C");
grados =Double.parseDouble(br.readLine());
// hacemos los calculos
double farenheit=grados*2-grados/5;
farenheit=farenheit+32;
// mostramos el resultado
System.out.println(grados+" C equivale a "+farenheit+" farenheit");
}
catch(Exception e)
{
System.err.println("\n\n" + e.toString() + "\n\n");
}
}
}

6. Leer tres nmeros diferentes (elaborar la validacin de datos) y


determinar el valor intermedio(el numero que no es mayor ni menor).
import java.io.*;
public class JavaApplication9 {
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int a = 10, b = 9, c = 11;
System.out.println("Ingresar el Primer Valor:");
a=Integer.parseInt(in.readLine());
System.out.println("Ingresar el Segundo Valor:");
b=Integer.parseInt(in.readLine());
System.out.println("Ingresar el Tercer Valor:");
c=Integer.parseInt(in.readLine());
int aux, medio;
if (a >= b)
{
aux = b;
b = a;
a = aux;
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

}
if (b >= c)
{
aux = c;
c = b;
b = aux;
}
if (a >= b)
{
medio = a;
} else
{
medio = b;
}
System.out.println("El nmero medio es " + medio);
}
}

7. Realizar un programa con el cual se lea la hora, los minutos y segundos


para luego mostrar su equivalente en segundos.
import java.io.*;
public class JavaApplication9 {
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int h; //h es la hora
int m; //m es minutos total
int s; //introduzca los segundos
System.out.println("introduzca la hora");
h = Integer.parseInt(in.readLine());
System.out.println("introduzca los minutos ");
m = Integer.parseInt(in.readLine());
System.out.println("introduzca los segundos ");
s = Integer.parseInt(in.readLine());
double st = (h*3600)+(m*60)+s; //donde st es la cantidad de segundos
total
System.out.println("La cantidad de segundos total de la hora son "+st);
}
}
8. Dado un numero x determinar si es mltiplo de otro numero y.
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

import java.io.*;
public class JavaApplication9 {
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int resto;
int numero1 = 0;
int numero2 = 0;
System.out.println("introduzca el Numero1");
numero1 = Integer.parseInt(in.readLine());
System.out.println("introduzca el Numero2");
numero2 = Integer.parseInt(in.readLine());
resto = numero1%numero2;
if (resto==0)
System.out.println(numero1 + " es mltiplo de " + numero2);
else
System.out.println(numero1 + " NO es mltiplo de " + numero2);
}
}
9. Dados tres nmeros, determinar el mayor y menor.
import java.io.*;
public class JavaApplication9 {
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int num1, num2, num3;
System.out.print ("Ingresa primer numero: ");
num1 = Integer.parseInt(in.readLine());
System.out.print ("Ingresa segundo numero: ");
num2 = Integer.parseInt(in.readLine());
System.out.print ("Ingresa tercer numero: ");
num3 = Integer.parseInt(in.readLine());
if ((num1 > num2) && (num1 > num3))
{
System.out.println ("El mayor es: " + num1);
if (num2 > num3) {
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

System.out.println ("El menor es: " + num3);


} else {
System.out.println ("El menor es: " + num2);
}
}
if ((num2 > num1) && (num2 > num3)) {
System.out.println ("El mayor es: " + num2);
if (num1 > num3) {
System.out.println ("El menor es: " + num3);
} else {
System.out.println ("El menor es: " + num1);
}
}
if ((num3 > num1) && (num3 > num2)) {
System.out.println ("El mayor es: " + num3);
if (num1 > num2) {
System.out.println ("El menor es: " + num2);
} else {
System.out.println ("El menor es: " + num1);
}
}
}
}
PROBLEMAS PROPUESTOS
1. Escribir un programa que pida una contrasea numerica y permita tres
intentos. Si el usuario ingresa la contrasea correcta, que se muestre
"Correcto!" y que ejecute un programa cualquiera, despus del mensaje.
En caso contrario el programa debe mostrar " Contrasea equivocada".
Posteriormente terminar el programa de inmediato.
import java.io.*;
import java.text.DecimalFormat;
public class JavaApplication9 {
static int cont=0;
public static void main(String args[])throws IOException
{
Validar();
}
public static void Validar() throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int x=1,opc=5,y=0;
double z=0;
DecimalFormat df = new DecimalFormat("0.00");
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

System.out.println("----------- Bienvenido -----------");


System.out.println("User: Natalia");
System.out.println("Contrasea ");
System.out.println("Ingresar la Contrasea:");
opc=Integer.parseInt(in.readLine());
if (opc==123)
{
System.out.println("Correcto!");
while (opc>3||opc<1)
{
System.out.println("----------- Tipo de Cambio -----------");
System.out.println("1. Suma");
System.out.println("2. Multiplicacion");
System.out.println("3. Salir");
System.out.println("Ingresar su opcion:");
opc=Integer.parseInt(in.readLine());
}
switch (opc)
{
case 1:
System.out.println("Ingresar la cantidad 1:");
x=Integer.parseInt(in.readLine());
System.out.println("Ingresar la cantidad 2:");
y=Integer.parseInt(in.readLine());
z=y + x;
System.out.println("La suma:" + z);
break;
case 2:
System.out.println("Ingresar la cantidad 1:");
x=Integer.parseInt(in.readLine());
System.out.println("Ingresar la cantidad 2:");
y=Integer.parseInt(in.readLine());
z=y * x;
System.out.println("La multiplicacion:" + df.format(z));
break;
case 3:
System.out.println("Usted salio");
break;
}
}
else
{
cont=cont+1;
if (cont==3)
{
System.out.println("Contrasea equivocada");
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

return ;
}
else
{
Validar();
}
}
}
}

2. Escribir un programa que lea una lista de nmeros y determine cuantos


son positivos, y cuantos son negativos.
import java.io.*;
public class JavaApplication9 {
public static void main(String args[])throws IOException
{
BufferedReader br;
int num[] = new int[200];
int n=0,p=0,ne=0;
br = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Cuantos numeros va ha ingresar a la lista");
n=Integer.parseInt(br.readLine());
for(int i=0; i<n;i++)
{
System.out.println("Numero "+(i));
num[i]=Integer.parseInt(br.readLine());
NATALIA ALEMN LPEZ

EJERCICIOS DE JAVA

if (num[i]>0)
p=p+1;
else
ne=ne+1;
}
System.out.println("Positivos " + p);
System.out.println("Negativos " + ne);
}
}

3. Obtener la serie: 1,-1,2,-2,3,-3, para n nmeros


import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int num[] = new int[200];
int n=0,p=1,ne=-1;
br = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Cuantos numeros quiere:");
n=Integer.parseInt(br.readLine());
for(int i=0; i<n; i=i+2)
NATALIA ALEMN LPEZ

1
0

EJERCICIOS DE JAVA

{
num[i]=p;
num[i+1]=ne;
p=p+1;
ne=ne+(-1);
}
for(int i=0; i<n;i++)
{
if ((i+1)==n)
{
System.out.print( num[i]);
}
else
{
System.out.print( num[i]+",");
}
}
}
}

4. Escribir un programa que permita obtener el valor aproximado de PI,


mediante la serie: 4 - 4/3 + 4/5 4/7 + 4/9 4/11 + para n trminos.
import java.io.*;
public class JavaApplication9
{ si
public static void main(String args[]) throws IOException
{
BufferedReader br;
int n,c=1,c1=1;
double pi;
double ne= 0.0, p = 0.0, x = 3.0, x1 = 5.0;
NATALIA ALEMN LPEZ

1
1

EJERCICIOS DE JAVA

br = new BufferedReader (new InputStreamReader (System.in));


System.out.println("Cuantos numeros quiere en la serie");
n=Integer.parseInt(br.readLine());
while(c <= n)
{
ne = ne + 4/x;
x = x+ 4.0;
p = p + 4/x1;
x1 = x1+ 4.0;
c = c+1;
}
pi = 4.0 - ne + p;
System.out.println("la serie de pi es: " + pi);
}
}

5. Escribir un programa que permita adivinar un numero que se genere


internamente al azar, el cual esta en el rango de 1 a 50. El usuario debe
adivinar este numero en base a aproximaciones, para lo cual se dispone
de 5 intentos. Ejemplo: Salida: Estoy pensando en un numero entre 1 y
50 Intento 1 ? 25 El numero esta entre 25 y 50 Intento 2 ?34 El numero
esta entre 34 y 50 Intento 3 ?45 El numero esta entre 34 y 45 Intento 4 ?
40 El numero esta entre 40 y 45 Intento 5 ?42 Si es correcto, que
muestre: Felicidades, adivinaste el numero De lo contrario: Se
acabaron los intentos, el numero que pens era 42.

NATALIA ALEMN LPEZ

1
2

EJERCICIOS DE JAVA

6. Escribir un programa que dados dos nmeros, uno real (base) y un


entero positivo (exponente), saque por pantalla todas las potencias con
base el numero dado y exponentes entre uno y el exponente
introducido.
import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int num[] = new int[200];
int n=0,p=1,ne=-1;
br = new BufferedReader (new InputStreamReader (System.in));
System.out.print("Introduzca un nmero real como base: ");
double base = Double.parseDouble(br.readLine());
System.out.print("Introduzca un mmero entero como exponente: ");
int exponenteFinal = Integer.parseInt(br.readLine());
double potencia;
int exponente;
for (int i = 1; i <= exponenteFinal; i++)
{
potencia = 1;
exponente = i;
for (int j = 0; j < exponente; j++) {
potencia *= base;
}
System.out.println(base + "^" + i + " = " + potencia);
}
}
}

NATALIA ALEMN LPEZ

1
3

EJERCICIOS DE JAVA

7. Generar las secuencia:


55555
4444
333
22
1
import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int num[] = new int[200];
int n=0,p=1,ne=-1;
br = new BufferedReader (new InputStreamReader (System.in));
n=5;
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print((i));
}
System.out.println();
}
}
}

NATALIA ALEMN LPEZ

1
4

EJERCICIOS DE JAVA

8. Generar la serie de Fibonacc


import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int numero,fibo1,fibo2,i;
do{
System.out.print("Introduce numero mayor que 1: ");
numero = Integer.parseInt(in.readLine());
}while(numero<=1);
System.out.println("Los " + numero + " primeros trminos de la serie de
Fibonacci son:");
fibo1=1;
fibo2=1;
System.out.print(fibo1 + " ");
for(i=2;i<=numero;i++){
System.out.print(fibo2 + " ");
fibo2 = fibo1 + fibo2;
fibo1 = fibo2 - fibo1;
}
System.out.println();
}
}
NATALIA ALEMN LPEZ

1
5

EJERCICIOS DE JAVA

9. Generar: 1,2,6,24,120, para n trminos


import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int n,g=1;
int num[] = new int[200];
br = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Cuantos numeros quiere en la serie");
n=Integer.parseInt(br.readLine());
for(int i=1; i<=n; i++)
{
num[i]=g*i;
g=num[i];
}
for(int i=1; i<n; i++)
{
if ((i+1)==n)
{
System.out.print( num[i]);
}
else
{
System.out.print( num[i]+",");
}
NATALIA ALEMN LPEZ

1
6

EJERCICIOS DE JAVA

}
}
}

10.Obtener el valor de la serie: 2,5,7,10,12,15,17,,1800


import java.io.*;
public class JavaApplication9
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int n,g=2,h=5;
int num[] = new int[10000];
br = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Cuantos numeros quiere en la serie");
n=Integer.parseInt(br.readLine());
for(int i=0; i<=n; i=i+2)
{
num[i]=g;
g=g+5;
}
for(int i=1; i<=n; i=i+2)
{
num[i]=h;
NATALIA ALEMN LPEZ

1
7

EJERCICIOS DE JAVA

h=h+5;
}
for(int i=0; i<n; i++)
{
if ((i+1)==n)
{
System.out.print( num[i]);
}
else
{
System.out.print( num[i]+",");
}
}
}
}

PROBLEMAS PROPUESTOS
1. Usando funciones y la sentencia switch, escribir un programa que pida
los datos necesarios y calcule el rea y el permetro para cada figura
indicada. a) Un cuadrado b) Un rectngulo c) Un tringulo d) Un crculo

NATALIA ALEMN LPEZ

1
8

EJERCICIOS DE JAVA

2. Elabore un programa que calcule el area de un triangulo mediante la


formula:

lados del triangulo. Para que el triangulo exista, debe cumplirse donde p
es el semiperimetro, p=(a+b+c)/2, siendo a, b, c los tres que los lados
sean todos positivos, y adems que la suma de dos lados cualesquiera
sea mayor que el otro lado.

3. Disear una funcin que calcule el promedio de varios nmeros


introducidos por el teclado. Hacer dos versiones, una para un nmero
fijo de valores y otra para un nmero cualquiera.de valores.

NATALIA ALEMN LPEZ

1
9

EJERCICIOS DE JAVA

4. Escribir una funcin que intercambie el valor de dos variables, es decir si


X=5 e Y=7 tras aplicar la funcin, por ejemplo haciendo
"intercambiar(X,Y)" se tiene que X=7 e Y=5.
public class JavaApplication9
{
public static void main(String args[])
{
int A, B, AUX;
A = 5;
B = 7;
System.out.println("Valores iniciales: A = " + A + " B = " + B);
Cambiar(A,B);
}
public static void Cambiar( int x , int y)
{
//instrucciones para hacer el intercambio
//se utiliza una variable auxiliar
int AUX;
AUX = x;
x = y;
y = AUX;
System.out.println("Valores intercambiados: A = " + x + " B = " + y);
}
}

NATALIA ALEMN LPEZ

2
0

EJERCICIOS DE JAVA

5. Disear una funcin que calcule la potencia ensima de un nmero, es


decir que calcule X n para X real y n entero.

6. Escriba una funcin VOID que obtenga la suma de los n primeros pares
primos.
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int num=0,res=0,contDiv=0;
System.out.println("Ingrese el nmero a calcular");
num= Integer.parseInt(in.readLine());
for(int i=1;i<=num;i++)
{
res=num % i;
if(res==0)
{
System.out.println(""+i);
contDiv++;
NATALIA ALEMN LPEZ

2
1

EJERCICIOS DE JAVA

}
}
if(contDiv==2)
System.out.println("El nmero "+ num + " es primo!");
else
System.out.println("El nmero "+ num + " no es primo!");
}
}

7. Leer un nmero entero y determinar si el mismo es un numero capica


emplear una funcin con retorno (1 si es capica, 0 si no lo es).
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
int n;
int valor=0;
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Introducir numero decimal entero:");
n=Integer.parseInt(in.readLine());
valor=capi(n);
NATALIA ALEMN LPEZ

2
2

EJERCICIOS DE JAVA

System.out.println ("\nRetorno " + valor);


}
public static int capi (int n)
{
int r,s=0,k, resultado;
k=n;
while(n!=0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
System.out.print("\nel numero invertido es :"+s);
if(s==k)
{
System.out.println ("\nEs capicua ");
resultado=1;
}
else
{
System.out.println ("\nNo es capicua ");
resultado=0;
}
return resultado;
}
}

NATALIA ALEMN LPEZ

2
3

EJERCICIOS DE JAVA

8. Escribir una funcin con retorno que encuentre la raz cuadrada de un


nmero empleando el mtodo de Newton.
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
double valor=0;
final double PRECISION = 1e-5;
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Ingrese nmero, Raz cuadrada mtodo Newton");
double numero=Double.parseDouble(in.readLine());
valor=raizCuadradaNewton(numero,1,PRECISION);
System.out.println("El valor es :" + valor);
}
public static double raizCuadradaNewton(double x, double aprox, double
precision)
{
double actualAprox = (aprox+(x/aprox))/2;
if(Math.abs(actualAprox - aprox) > precision) {
return raizCuadradaNewton(
x,actualAprox,precision);
}
return actualAprox;
}
}

NATALIA ALEMN LPEZ

2
4

EJERCICIOS DE JAVA

9. Escribir una funcin con retorno para determinar si 3 nmeros ledos


desde el teclado forman un triangulo (retornar 1 si as lo fueran y 0 de
no ser as), luego mediante una segunda funcin con retorno determinar
si forman un triangulo equiltero (1), issceles(2) o escaleno (3). Los
valores que aparecen entre parntesis son los valores a retornar.

import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int x,y,z;
System.out.println("Escribe el primer lado:");
x=Integer.parseInt(in.readLine());
System.out.println("Escribe el segundo lado:");
y=Integer.parseInt(in.readLine());
System.out.println("Escribe el tercer lado:");
z=Integer.parseInt(in.readLine());
/*Comprobacin de si es un tingulo,
damos por hecho que los nmeros son positivos */
if ((x+y>z) && (x+z>y) && (y+z)>x)
{
if (x==y && x==z)
System.out.println ("Equiltero");
else
if (x==y || x==z || y==z)
System.out.println ("Issceles");
else
System.out.println("Escaleno");
}
else
System.out.println("Esos nmeros no forman un tringulo");
}
}
NATALIA ALEMN LPEZ

2
5

EJERCICIOS DE JAVA

PROBLEMAS PROPUESTOS
1. escriba un programa que permita encontrar la sumatoria de los nmeros
impares comprendidos desde 50 a 1000 guardados en un arreglo
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
int num[] = new int[2000];
int suma=0;
int c=50;
for (int i=0; i<=1050; i++)
{
num[i]=c;
if (num[i]%2!=0)
{
suma=suma+num[i];
}
c=c+1;
NATALIA ALEMN LPEZ

2
6

EJERCICIOS DE JAVA

}
System.out.println("La sumatoria es: " + suma);
}
}

2. elabore un programa que permita introducir 20 elementos de tipo


entero en un arreglo, el programa mostrara impreso el arreglo en orden
inverso
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
int num[] = new int[2000];
int suma=0,total;
int c=50;
total=20;
for (int i=1; i<=total; i++)
{
//Guardo los datos
num[i]=(i);
}
NATALIA ALEMN LPEZ

2
7

EJERCICIOS DE JAVA

for (int i=total; i>=1; i--)


{
//Muestro los datos
if ((i)==1)
{
System.out.print( num[i]);
}
else
{
System.out.print( num[i]+",");
}
}
}
}

3. elabore un programa que permita encontrar el primer y segundo mayor


de un arreglo de 15 elementos
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Ingrese cantidad de numeros a introducir");
int n = Integer.parseInt(in.readLine());
NATALIA ALEMN LPEZ

2
8

EJERCICIOS DE JAVA

int[] array = new int[n];


for(int i = 0;i < array.length; i++)
{
System.out.print("Ingrese "+(i+1)+": ");
array[i] = Integer.parseInt(in.readLine());
}
System.out.println("El Primero mayor de la lista es:
"+array[indicePrimero(array)]);
System.out.println("El Segundo mayor de la lista es:
"+array[indiceSegundo(array)]);
}
// Funcion para encontrar el Indice del primer mayor
private static int indicePrimero(int[] array)
{
int mayor = -2147483648;
int indice = -1;
for(int i = 0;i < array.length; i++)
{
if( mayor < array[i] )
{
mayor = array[i];
indice = i;
}
}
return indice;
}
// Funcion para encontrar el Indice del segundo mayor
private static int indiceSegundo(int[] array)
{
int primerMayor = indicePrimero(array); // Buscamos el mayor
int temporal=array[primerMayor]; // Almacenamos su valor en
"temporal"
array[primerMayor] = -2147483648; // Y le asignamos el ms pequeo
numero posible en programacion
// lo ideal seria -infinito (menos infinito)
int segundoMayor = indicePrimero(array); // Buscamos el mayor, (El
primer mayor lo marcamos como el numero pequeo
array[primerMayor] = temporal; // Restablecemos el primer mayor.
return segundoMayor; // Retornamos el indice del segundo mayor
}
}

NATALIA ALEMN LPEZ

2
9

EJERCICIOS DE JAVA

4. hacer un programa que lea diez valores enteros en un array y los


muestre en pantalla. despus que los ordene de menor a mayor y los
vuelva a mostrar. y finalmente que los ordene de mayor a menor y los
muestre por tercera vez. para ordenar la lista usar una funcin que
implemente el mtodo de la burbuja

5. elabore un programa que imprima en orden inverso una cadena de


caracteres
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
NATALIA ALEMN LPEZ

3
0

EJERCICIOS DE JAVA

{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Ingrese la cadena a introducir");
String sCadena =in.readLine();
String sCadenaInvertida = "";
for (int x=sCadena.length()-1;x>=0;x--)
{
sCadenaInvertida = sCadenaInvertida + sCadena.charAt(x);
}
System.out.println("La cadena inversa: " + sCadenaInvertida);
}
}

8. Elabore un programa que permita introducir un arreglo de 25 elementos


de tipo entero luego pedir al usuario que introduzca un nmero, el
programa mostrara el nmero de veces que se repite dicho valor en el
arreglo.
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
int n = 25;
int frecuenciaTemp, frecuencia = 0;
NATALIA ALEMN LPEZ

3
1

EJERCICIOS DE JAVA

System.out.println("Ingrese cantidad de numeros a introducir " + n );


int[] array = new int[n];
for(int k = 0;k < array.length; k++)
{
System.out.print("Ingrese "+(k+1)+": ");
array[k] = Integer.parseInt(in.readLine());
}
for (int i=0; i < array.length-1; i++){
frecuenciaTemp = 1;
for(int j = i+1 ; j< array.length; j++)
{
if(array[i] == array[j])
frecuenciaTemp ++;
}
if(frecuenciaTemp > frecuencia)
{
frecuencia = frecuenciaTemp;
}
}
System.out.println("El numero de veces que se repite: " + frecuencia);
}
}

9. Elabore un programa que permita encontrar el primer y segundo menor


de un arreglo de 15 elementos.

NATALIA ALEMN LPEZ

3
2

EJERCICIOS DE JAVA

import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Ingrese cantidad de numeros a introducir");
int n = Integer.parseInt(in.readLine());
int[] array = new int[n];
for(int i = 0;i < array.length; i++)
{
System.out.print("Ingrese "+(i+1)+": ");
array[i] = Integer.parseInt(in.readLine());
}
System.out.println("El Primero mayor de la lista es:
"+array[indicePrimero(array)]);
System.out.println("El Segundo mayor de la lista es:
"+array[indiceSegundo(array)]);
}
// Funcion para encontrar el Indice del primer menor
private static int indicePrimero(int[] array)
{
int mayor = array.length;
int indice = -1;
for(int i = 0;i < array.length; i++)
{
if( mayor >= array[i] )
{
mayor = array[i];
indice = i;
}
}
return indice;
}
// Funcion para encontrar el Indice del segundo mayor
private static int indiceSegundo(int[] array)
{
int primerMenor = indicePrimero(array);
int temporal=array[primerMenor];
array[primerMenor] = array.length;
int segundoMenor = indicePrimero(array);
array[primerMenor] = temporal;
return segundoMenor;
}
}
NATALIA ALEMN LPEZ

3
3

EJERCICIOS DE JAVA

10.elabore un programa que permita introducir un arreglo de 8 elementos


de tipo entero. el programa mostrara un arreglo en donde muestre un 1
para los primos y un 0 para los no primos
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader br;
int n,c;
int vec[]= new int[100];
int vec2[]= new int[100];
br = new BufferedReader (new InputStreamReader (System.in));
for (int i=0;i<8;i++)
{
System.out.print(" Ingrese el " + (i+1) +" del vector ");
vec[i]=Integer.parseInt(br.readLine());
}
for (int i=0;i<8;i++)
{
c=0;
for(int j=vec[i]; j>=1;j--)
NATALIA ALEMN LPEZ

3
4

EJERCICIOS DE JAVA

{
if((vec[i]%j)==0)
c++;
}
if(c==2)
vec2[i]=1;
else
vec2[i]=0;
}
for (int i=0;i<8;i++)
{
System.out.println(vec[i]+ " "+ vec2[i]);
}
}
}

PROBLEMAS PROPUESTOS
1. Dadas 2 matrices de orden n*n, obtener la suma de las mismas
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in = new BufferedReader (new InputStreamReader (System.in));
int[][]a=new int[100][100];
int[][]b=new int[100][100];
NATALIA ALEMN LPEZ

3
5

EJERCICIOS DE JAVA

int[][]ca=new int[100][100];
int f=0,c=0,resp,aux,x,y,suma=0;
int fi,co;
System.out.println("Ingrese las filas y columnas de las 2 matrices(deben
ser iguales para que se puedan sumar)");
fi =Integer.parseInt(in.readLine());
co =Integer.parseInt(in.readLine());
System.out.println("MATRIZ 1");
for(int ig=1;ig<=fi;ig++)
{
System.out.println("Ingrese la fila: "+ig);
for(int jg=1;jg<=co;jg++)
{
a[ig][jg]=Integer.parseInt(in.readLine());
}
}
System.out.println("\n MATRIZ 2");
for(int ih=1;ih<=fi;ih++)
{
System.out.println("Ingrese la fila: "+ih);
for(int jh=1;jh<=co;jh++)
{
b[ih][jh]=Integer.parseInt(in.readLine());
}
}
for(int iq=1;iq<=fi;iq++)
{
for(int jq=1;jq<=co;jq++)
{
ca[iq][jq]=a[iq][jq]+b[iq][jq];
}
}
for(int qqa=1;qqa<=fi;qqa++)
{
for(int wwa=1;wwa<=co;wwa++)
{
System.out.print(" "+ca[qqa][wwa]);
}
System.out.println("");
}
}
}

NATALIA ALEMN LPEZ

3
6

EJERCICIOS DE JAVA

2. Generar la siguiente matriz de orden n*n:

import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader in;
in = new BufferedReader (new InputStreamReader (System.in));
int[][]a=new int[100][100];
int[][]b=new int[100][100];
int[][]ca=new int[100][100];
int f=0,c=0,resp,aux,x,y,suma=0;
int fi,co;
System.out.println("Ingrese las filas y columnas de las 2 matrices");
fi =Integer.parseInt(in.readLine());
co =Integer.parseInt(in.readLine());
System.out.println("MATRIZ");
for(int ig=1;ig<=fi;ig++)
{
System.out.println("Ingrese la fila: "+ig);
for(int jg=1;jg<=co;jg++)
{
a[ig][jg]=Integer.parseInt(in.readLine());
NATALIA ALEMN LPEZ

3
7

EJERCICIOS DE JAVA

}
}
for(int iq=1;iq<=fi;iq++)
{
for(int jq=1;jq<=co;jq++)
{
ca[iq][jq]=a[iq][jq];
}
}
for(int qqa=1;qqa<=fi;qqa++)
{
for(int wwa=1;wwa<=co;wwa++)
{
System.out.print(" "+ca[qqa][wwa]);
}
System.out.println("");
}
}
}

3. Generar la siguiente matriz:

NATALIA ALEMN LPEZ

3
8

EJERCICIOS DE JAVA

4. Generar la siguiente matriz de orden n*n:

5. Realice un programa para invertir una matriz mediante un mtodo


distinto al de Faddevva
import java.io.*;
public class JavaApplication9
{
public static void main(String args[]) throws IOException
{
BufferedReader br;
int n,n2,c=1,c1=1;
double pi;
double ne= 0.0, p = 0.0, x = 3.0, x1 = 5.0;
br = new BufferedReader (new InputStreamReader (System.in));
do
{
System.out.print("Introduzca el valor de 'n': ");
n=Integer.parseInt(br.readLine());
}
while((n%2) != 0);

NATALIA ALEMN LPEZ

3
9

EJERCICIOS DE JAVA

int arr[][] = new int[n][n];


for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < arr[0].length; j++)
{
System.out.println("Introduzca el valor de arr["+i+"]["+j+"]: ");
arr[i][j] = Integer.parseInt(br.readLine());
}
}
int l = 0;
int m = 0;
int inver[][] = new int[n][n];
for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < arr[0].length; j++)
{
inver[l][m] = arr[i][j];
l++;
}
l = 0;
m++;
}
//Para verificar que efectivamente se elabor la inversa de la matriz.
for(int i = 0; i < inver.length; i++)
{
for(int j = 0; j < inver[0].length; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}

int cont = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(arr[i][j] == inver[i][j])
cont++;
}
}
}
}
NATALIA ALEMN LPEZ

4
0

EJERCICIOS DE JAVA

6. Realice un programa para generar la siguiente matriz de orden n*n:

7. Realice un programa que genere una matriz en la que se guarden los


datos de las ventas de 6 vendedores de la siguiente manera:
Cantidad Vendida Vendedor 1 Cantidad vendida
Vendedor 2
Toyota
Peugeot
Mazda
Ford

NATALIA ALEMN LPEZ

4
1

EJERCICIOS DE JAVA

Mitsubishi
Luego mostrar la cantidad de ventas por marca de cada vendedor y mostrar
al que mas haya vendido y al que menos haya vendido

8. Crear un programa que genere aleatoriamente una eleccin presidencial


de la siguiente manera:
MNR ADN MIR MAS

Una vez llenada la tabla, mostrar que partido tuvo mas


votos en cada departamento y que partido gana a nivel nacional y con que
porcentaje de los votos.

9. Realice un programa para generar la siguiente matriz de orden n*n:

NATALIA ALEMN LPEZ

4
2

EJERCICIOS DE JAVA

10.Realice un programa que reemplace todos los lugares en los que la fila y
la columna sumadas sumen el orden de la matriz por el orden de la
matriz. Se debe tomar como posicin inicial.

PROBLEMAS PROPUESTOS
1. Mediante un programa recursivo determine si un numero n, ingresado
por teclado es primo o no.

NATALIA ALEMN LPEZ

4
3

EJERCICIOS DE JAVA

2. Disee e implemente un mtodo recursivo que nos permita obtener el


determinante de una matriz cuadrada de dimensin n

3. Implemente, de forma recursiva, una funcin que le d la vuelta a una


cadena de caracteres

4. Mediante un programa recursivo calcule la divisin de 2 nmeros


mediante restas sucesivas

NATALIA ALEMN LPEZ

4
4

EJERCICIOS DE JAVA

5. Disea un algoritmo recursivo que lea una secuencia de caracteres de


longitud arbitraria terminada en un punto, e imprima la suma de todos
los dgitos junto con la sucesin en orden inverso de entrada

6. Escribe un algoritmo recursivo que ordene un array de la siguiente


forma: a) Sea k el ndice del elemento mitad del array. b) Ordena los
elementos hasta a[k], incluyndolo. c) Ordena los elementos siguientes.
d) Mezcla los dos subarrays en un nico array ordenado. Este mtodo de
clasificacin interna se denomina "Mergesort".

NATALIA ALEMN LPEZ

4
5

EJERCICIOS DE JAVA

7. Disea un algoritmo recursivo que, dado un array de enteros, devuelva


el k- simo elemento ms pequeo del array, es decir, si el array
contiene los elementos (4,7,3,6,8,1,9,2) y k=5, el algoritmo debera
devolver 6.

8. Implementa el algoritmo de bsqueda binaria de forma recursiva.


import java.io.*;
public class JavaApplication9
{
NATALIA ALEMN LPEZ

4
6

EJERCICIOS DE JAVA

public static void main(String args[]) throws IOException


{
BufferedReader br;
br=new BufferedReader(new InputStreamReader(System.in));
String mensaje="";
int[]vector
={1,4,7,8,9,14,23,47,56,60,61,63,65,66,68,69,70,73,76,77,79,80,82};
System.out.println("Ingresar el numero a buscar:");
int valorBuscado = Integer.parseInt(br.readLine());;
mensaje=busquedaBinaria(vector,valorBuscado);
System.out.println(mensaje);
}
public static String busquedaBinaria(int vector[], int dato){
int n = vector.length;
int centro,inf=0,sup=n-1;
String mensaje="No esiste";
while(inf<=sup){
centro=(sup+inf)/2;
if(vector[centro]==dato)
mensaje="Si existe";
else if(dato < vector [centro] ){
sup=centro-1;
}
else {
inf=centro+1;
}
}
return mensaje;
}
}

NATALIA ALEMN LPEZ

4
7

EJERCICIOS DE JAVA

9. Mediante un programa recursivo, determinar si un numero es capica o


no.

10.Generar el triangulo de Pascal para n filas utilizando funciones recursivas

NATALIA ALEMN LPEZ

4
8

EJERCICIOS DE JAVA

NATALIA ALEMN LPEZ

4
9

También podría gustarte